mirror of
https://github.com/kennethreitz/responder.git
synced 2026-06-05 23:00:17 +00:00
Improve exception handling
Re-raise exceptions caught in _dispatch_request. Added starlette ExceptionMiddleware to be able to test this gracefully.
This commit is contained in:
+6
-1
@@ -15,6 +15,7 @@ from starlette.testclient import TestClient
|
||||
from starlette.middleware.gzip import GZipMiddleware
|
||||
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
from starlette.exceptions import ExceptionMiddleware
|
||||
from apispec import APISpec
|
||||
from apispec.ext.marshmallow import MarshmallowPlugin
|
||||
from apispec import yaml_utils
|
||||
@@ -31,6 +32,7 @@ from .statics import (
|
||||
DEFAULT_API_THEME, DEFAULT_SESSION_COOKIE, DEFAULT_SECRET_KEY, DEFAULT_CORS_PARAMS
|
||||
)
|
||||
|
||||
|
||||
# TODO: consider moving status codes here
|
||||
class API:
|
||||
"""The primary web-service class.
|
||||
@@ -121,6 +123,7 @@ class API:
|
||||
|
||||
if self.cors:
|
||||
self.add_middleware(CORSMiddleware, **self.cors_params)
|
||||
self.add_middleware(ExceptionMiddleware, debug=debug)
|
||||
|
||||
# Jinja enviroment
|
||||
self.jinja_env = jinja2.Environment(
|
||||
@@ -285,6 +288,7 @@ class API:
|
||||
cont = True
|
||||
except Exception:
|
||||
self.default_response(req, resp, error=True)
|
||||
raise
|
||||
|
||||
elif route.is_class_based or cont:
|
||||
try:
|
||||
@@ -301,8 +305,9 @@ class API:
|
||||
# If it's async, await it.
|
||||
if hasattr(r, "send"):
|
||||
await r
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
self.default_response(req, resp, error=True)
|
||||
raise
|
||||
|
||||
# Then on_get.
|
||||
method = req.method
|
||||
|
||||
@@ -3,6 +3,8 @@ import yaml
|
||||
import responder
|
||||
import io
|
||||
|
||||
from starlette.responses import PlainTextResponse
|
||||
|
||||
|
||||
def test_api_basic_route(api):
|
||||
@api.route("/")
|
||||
@@ -460,12 +462,18 @@ def test_file_uploads(api):
|
||||
|
||||
|
||||
def test_500(api):
|
||||
def catcher(request, exc):
|
||||
return PlainTextResponse("Suppressed error", 500)
|
||||
|
||||
api.app.add_exception_handler(ValueError, catcher)
|
||||
|
||||
@api.route("/")
|
||||
def view(req, resp):
|
||||
raise ValueError
|
||||
|
||||
r = api.requests.get(api.url_for(view))
|
||||
assert not r.ok
|
||||
assert r.content == b'Suppressed error'
|
||||
|
||||
|
||||
def test_404(api):
|
||||
|
||||
Reference in New Issue
Block a user