Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to write a custom error handler #1

Open
cdruet opened this issue Dec 10, 2020 · 1 comment
Open

How to write a custom error handler #1

cdruet opened this issue Dec 10, 2020 · 1 comment

Comments

@cdruet
Copy link

cdruet commented Dec 10, 2020

Great module. Very useful.

I'ld like to customise the handler for 500 to do a rollback. It should be available to all blueprints (in my case) but there could be a use for specifying which blueprints use this customised handler.

In the intro, you explicitly mention that:

Instead you can use your own response implementation passed as argument to ErrorHandler class: it must be a decorator and must take 3 args, a dict response, status code and dict headers.

Could you tell me a bit more about how to do that? Would you have a small example?

@cs91chris
Copy link
Owner

cs91chris commented Dec 11, 2020

Hi, for a customised error response available to all blueprint you have to implement a function with the same interface of this, for example:

def response_builder(self, f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        r, s, h = f(*args, **kwargs)
        # your own custom implementation
        return flask.Response(...)

    return wrapper

and use with:

error = ErrorHandler()
error.init_app(app, response=response_builder)

Instead for a specific blueprint called custom_bp, decorate your custom function, like this:

@error.register(custom_bp)
def custom_error_handler(exc):
    return str(exc), 500, {'Content-Type': 'text/plain'}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants