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

Issue with Flask exception handler when running via gunicorn #3345

Open
PavloPanchyshak opened this issue Feb 10, 2025 · 0 comments
Open

Issue with Flask exception handler when running via gunicorn #3345

PavloPanchyshak opened this issue Feb 10, 2025 · 0 comments

Comments

@PavloPanchyshak
Copy link

PavloPanchyshak commented Feb 10, 2025

Issue with Flask Exception Handler When Running via Gunicorn

Environment

  • Python 3.11.2
  • Gunicorn: 23.0.0
  • Flask: 2.2.5
  • Flask Extensions:
    • Flask-RESTx: 1.3.0
    • Flask-Cors: 4.0.0
    • Flask-Migrate: 4.0.7
    • Flask-Pydantic: 0.12.0
    • Flask-SocketIO: 5.5.1
    • Flask-SQLAlchemy: 3.1.1
    • Flask-SSE: 1.0.0

Problem Description

I have a Flask application with a global exception handler defined as follows:

@app.errorhandler(Exception)
def handle_generic_exception(error):
    traceback.print_exc()
    return Response(
        status=ExceptionType.GENERIC_EXCEPTION.http_status,
        mimetype='application/json',
        response=json.dumps({
            'error': ExceptionType.GENERIC_EXCEPTION.message,
        }),
    )

Additionally, I have a simple route that raises an exception:

@app.route("/")
def hello_world():
    raise Exception('Not Work')
    return json.dumps({"message": "Hello, World!"})

Expected Behavior

When running the application locally using:

app.run(host="0.0.0.0", port=8000, debug=settings.IS_LOCAL)

the exception handler works correctly, and a JSON response with the defined error message is returned.

Issue

However, when running the application via Gunicorn:

gunicorn -w 4 grade_wiz.grade_wiz:app --timeout 3600 --keep-alive 5 --log-level info --bind=0.0.0.0:8000

the @app.errorhandler(Exception) does not catch the exception, and a standard HTTP 500 response is returned instead.

Requested Help

How can I properly configure exception handling in Flask so the handler works correctly when running via Gunicorn?

Any advice or guidance on possible solutions would be greatly appreciated.

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

1 participant