Category: python
error handling and custom error responses
Published on 30 Sep 2026
Explanation
Flask allows applications to handle exceptions globally instead of returning unstructured error pages.
Code:
@app.errorhandler(404)
def not_found(error):
return {'error': 'Resource not found'}, 404
Explanation
Custom error handlers can return consistent JSON responses for REST APIs.
Code:
@app.errorhandler(500)
def server_error(error):
return {
'error': 'Internal server error'
}, 500
Explanation
abort() can stop request processing and return a specific HTTP error status.
Code:
from flask import abort
@app.get('/users/<int:id>')
def get_user(id):
if id != 101:
abort(404)
return {'id': id}
Explanation
Application code can catch known exceptions and return meaningful error responses.
Code:
@app.route('/divide')
def divide():
try:
result = 10 / 0
return {'result': result}
except ZeroDivisionError:
return {'error': 'Cannot divide by zero'}, 400
Explanation
A consistent error format makes it easier for frontend applications to process API errors.
Code:
{
"error": "VALIDATION_ERROR",
"message": "Email is required",
"status": 400
}