Allow flask to handle exceptions with gunicorn

Dash version: 2.16.1

Hi everyone,

Dash ignores my flask errorhandler when I run it with gunicorn. It seems that gunicorn is overwriting the flask errorhandler to print the exceptions to stderr. Here is my implementation:

from urllib.parse import urlparse
import dash
from flask import jsonify, request

app = dash.Dash(__name__)

server = app.server

@server.errorhandler(Exception)
def handle_exceptions(e):
    return jsonify(error=str(e)), e.response.status_code

@server.after_request
def redirect_if_not_auth(response):
    if request.path == "/_dash-update-component" and request.method == "POST":
        if response.status_code == 403:
            search = urlparse(request.referrer).path
            href = "{}?{}={}".format("/login", "next", search)
            return jsonify(
                {
                    "multi": True,
                    "response": {"url-redirect": {"href": href}},
                }
            )

    return response

def main():
    app.run(debug=True)

if __name__ == "__main__":
    main()

I run gunicorn as follows:

gunicorn myapp:server --bind localhost:8000 -chdir /path/to/project --workers 2

Is it possible to force gunicorn to use flask errorhandler?

Hello @Bassandj,

When are you expecting your exception to trigger?

You can decorate the callbacks and layouts in order to handle exceptions from dash if you need.

@jinnyzor thanks for your reply and my bad, I realized that my mistake was that the app.server object did not contain the error handler.

To be short, our app configuration had three main files:

  • server.py for the server configuration (and loggers)
  • run_wsgi.py to run the app
  • index.py to register the callbacks and layouts

Both the “index.py” and “run_wsgi.py” were importing the app.server object from “server.py”. The error was that the server errorhandler was written in the “run_wsgi.py” file, while the app was run from the index file (gunicorn index:server). Of course, the server object in “index.py” was not containing the errorhandler :face_with_peeking_eye:

To answer your question, I handle requests.exceptions.HTTPError exceptions when a request to the backend returned a 403 response. You mentioned it is possible to decorate a callback with an exception handler? do you have any reference for that?

Check out here:

1 Like

Wow thank you so much! This is very helpful!

1 Like