responder
responder copied to clipboard
Adding exception handler middleware
What is the recommended way to add exception handlers in responder?
It looks like Starlette allows this but as far as I can tell it it's not exposed in responder.
I'm looking for something like Flask's signal error handler syntax.
@app.errorhandler(InvalidRequest)
def invalid_request_handler(exc):
resp_data = {'status': 'error', 'errors': [e for e in exc.errors]}
return json.dumps(resp_data), exc.status_code, {}
Starlette has app.add_exception_handler()
. Is this something that can be easily exposed like app.add_middleware()
is?
I cannot use the builtin HTTPException
that comes with Starlette because I can't customize how the data is returned.
Is Starlette's app.add_exception_handler()
available somewhere in the guts of responder? I'd be happy accessing it via unconventional means for now.
for my use case I would really need a functionality along the lines of falcon.API.add_error_handler
. Starlette's app.add_exception_handler()
seems like a very close match, if I'm not wrong.
Here's the part of the API
class where middleware is being registered. I can't find a way to insert my own exception handling middleware without changing api.py directly.
Is this supported?
self.add_middleware(GZipMiddleware)
if self.hsts_enabled:
self.add_middleware(HTTPSRedirectMiddleware)
self.add_middleware(TrustedHostMiddleware, allowed_hosts=self.allowed_hosts)
self.lifespan_handler = LifespanMiddleware(LifespanHandler)
if self.cors:
self.add_middleware(CORSMiddleware, **self.cors_params)
self.add_middleware(ServerErrorMiddleware, debug=debug)
Starlette (where ServerErrorMiddleware
comes from) supports custom exception handlers but it seems responder doesn't initialize a Starlette app? Without it I can't use their app.add_exception_handler
function.
https://www.starlette.io/applications/#customizing-exception-handling
Some guidance would be welcome!
So far, there is no reliable exception_handler way to unify the management of server exception response.