This is an issue when a Flask error handler returns a response without explicitly specifying the HTTP status code.

Why is this an issue?

Flask error handlers do not automatically set the HTTP status code based on the error type they handle. When you register an error handler with @app.errorhandler(404), Flask does not automatically return a 404 status code from that handler.

Instead, Flask will return a 200 OK status code by default, unless you explicitly specify the correct status code in the response. This creates a mismatch between the intended error condition and the actual HTTP response.

This behavior can break client applications that rely on HTTP status codes to handle different error scenarios. For example, a client expecting a 404 status code to handle "not found" cases will not work correctly if the server returns 200 OK instead.

The Flask documentation explicitly states: "The status code of the response will not be set to the handler’s code. Make sure to provide the appropriate HTTP status code when returning a response from a handler."

What is the potential impact?

Client applications may not handle errors correctly, leading to unexpected behavior. API consumers might not recognize error conditions, and automated tools or frameworks that depend on proper HTTP status codes may malfunction.

How to fix it in Flask

Add the appropriate HTTP status code as a second element in the return tuple. The status code should match the error type handled by the decorator.

Code examples

Noncompliant code example

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html')  # Noncompliant

Compliant solution

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

For error handlers returning JSON responses, also include the status code explicitly.

Noncompliant code example

@app.errorhandler(500)
def internal_error(e):
    return jsonify(error="Internal server error")  # Noncompliant

Compliant solution

@app.errorhandler(500)
def internal_error(e):
    return jsonify(error="Internal server error"), 500

When using register_error_handler(), the same principle applies - always specify the status code.

Noncompliant code example

def handle_bad_request(e):
    return 'Bad request!'  # Noncompliant

app.register_error_handler(400, handle_bad_request)

Compliant solution

def handle_bad_request(e):
    return 'Bad request!', 400

app.register_error_handler(400, handle_bad_request)

Resources

Documentation

Flask Error Handling Documentation - Official Flask documentation on handling application errors and registering error handlers