Search code examples
flasksentry

Flask: How do you render a custom error page AND get a Sentry alert?


I'm new to Flask, but have been using Django for years, so I'm confused as to why this behaves so differently.

I want any old generic exception that would have otherwise gone uncaught and propagated all the way to Gunicorn to instead be handled by both a custom Flask error handler and for it to trigger a Sentry alert.

This is trivial in Django, but unfortunately I have not found any way to do this in Flask. Sentry apparently works at the WSGI level, which seems to mean that if I have an exception handler set up in Flask (see below), the exceptions I catch in order to print a custom error page never make it to Sentry at all.

@app.errorhandler(Exception)
def internal_server_error(error):
    template_name, context = ErrorPages().error500(error)
    return (render_template(template_name, **context), 500)

The ErrorPages.error500() method takes the exception that the handler caught and prints a stacktrace into a custom template that fits the site's theme. So the user isn't presented with a scary blank white void with nothing but "INTERNAL SERVER ERROR".

If this handler code is active, I get nice error pages, but no Sentry alerts. If I comment it out, I get Sentry alerts, but no nice error pages.

How do I get both a custom error page and a Sentry alert?


Solution

  • You can use method capture_exception in function internal_server_error:

    from sentry_sdk import capture_exception
    
    @app.errorhandler(Exception)
    def internal_server_error(error):
        capture_exception(error)
        template_name, context = ErrorPages().error500(error)
        return (render_template(template_name, **context), 500)
    

    Link on documentation