aws / chalice

Python Serverless Microframework for AWS
Apache License 2.0
10.61k stars 1.01k forks source link

[Proposal] Allow for registration of custom error handlers #2056

Open cloutierMat opened 1 year ago

cloutierMat commented 1 year ago

I first put my proposal in response to #1884. But in an effort to make sure the work I do is in a desired direction, I am copying my comments here so that it can be seen and hopefully handled.

Problem

While the ChaliceUnhandledError works fine for custom errors, third party libraries can raise Exceptions that can't be subclassed. Having a try/except in a middleware won't successfully catch the Exception as it is already a Response at that point.

Goals

Specification

A new @app.errorhandler is to be added. The decorated function will take one arg, the exception.

Similar to the way middlewares can be registered, we will be able to register the error handler in app or in a blueprint with either a decorator or app.register_error.

# Decorator
@app.errorhandler(MyCustomError)
def my_handler(e: MyCustomError):
    return Response(body="", status_code:400)

# Register
app.register_error_handler(MyCustomError, my_handler)

# Blueprint
@my_blueprint.errorhandler(MyCustomError)
def my_handler(e: MyCustomError):
    return Response(body="", status_code:400)
In the examples above, any http endpoint raising MyCustomError will then return a 400 with no body.

If, however, the return value isn't a Response or an exception was raised during execution of the handler, the normal flow of the RestAPIEventHandler will be maintained.

@app.errorhandler(MyCustomError)
def my_handler(e: MyCustomError):
    return "Not a Response object"

Will return

{
    "Code": "InternalServerError",
    "Message": "An internal server error occurred."
}