Skip to content

Error handlers return wrong http status code #264

Description

@nioncode

There were multiple issues in the past that discuss error handlers and unhandled exceptions, but I couldn't find one that exactly matches my problem: I have a global error handler set up that looks like this:

def create_app():
    app = Flask(__name__)
    CORS(app)

    from . import routes
    routes.bp.url_prefix = app.config["BASE_URL"]
    app.register_blueprint(routes.bp)

    @app.errorhandler(Exception)
    def on_error(e):
        if isinstance(e, HTTPException):
            return jsonify({'error': e.code}), e.code

        return jsonify({'error': 500}), 500

    return app

The problem now is that whenever the browser sends an OPTIONS request to a route that does not exist, this will generate a HTTPException that gets wrapped into a JSON response by the errorhandler. The response headers then contain CORS headers, but still with HTTP status code 404 instead of 200, which makes the browser reject the request.

This by itself would be no problem, but, this also leads to the problem that the client does not receive the actual error code (404), because the browser shields this information and just says 'CORS request failed' without providing more information.

I fixed this problem by annotating the on_error method with the @cross_origin() decorator. Is this the expected behavior and if yes, could this please be added to the documentation? I thought using CORS(app) would enable this handling for all routes, all handlers, and everything.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions