This is an issue when a Flask error handler returns a response without explicitly specifying the HTTP status code.
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."
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.
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.
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html') # Noncompliant
@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.
@app.errorhandler(500)
def internal_error(e):
return jsonify(error="Internal server error") # Noncompliant
@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.
def handle_bad_request(e):
return 'Bad request!' # Noncompliant
app.register_error_handler(400, handle_bad_request)
def handle_bad_request(e):
return 'Bad request!', 400
app.register_error_handler(400, handle_bad_request)
Flask Error Handling Documentation - Official Flask documentation on handling application errors and registering error handlers