Last modified: Nov 15, 2024 By Alexander Williams

Flask Error Handler: Customize HTTP Error Pages Like a Pro

In Flask applications, handling errors gracefully is crucial for providing a better user experience. The app.errorhandler() decorator allows you to create custom error pages for different HTTP status codes.

Understanding Error Handlers

Error handlers in Flask intercept specific HTTP errors and allow you to customize the response. This is particularly useful when you want to maintain your application's look and feel even when errors occur.

Similar to how Flask before_request handles requests before they're processed, error handlers manage what happens when things go wrong.

Basic Error Handler Implementation


from flask import Flask, render_template

app = Flask(__name__)

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

@app.route('/')
def home():
    return 'Welcome to the homepage!'

if __name__ == '__main__':
    app.run(debug=True)

Creating Custom Error Templates

Create a template file (404.html) in your templates directory to display a custom error page:








    Page Not Found


    

Oops! Page Not Found

The requested page could not be found.

Return to Homepage

Handling Multiple Error Types

You can handle different types of errors by creating multiple error handlers. This provides a consistent experience across various error scenarios.


@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_error(error):
    return render_template('500.html'), 500

@app.errorhandler(403)
def forbidden_error(error):
    return render_template('403.html'), 403

Adding Custom Error Messages

You can pass additional context to your error templates using Flask make_response for more detailed error information:


@app.errorhandler(404)
def not_found_error(error):
    error_message = {
        'status_code': 404,
        'message': 'The requested resource was not found'
    }
    return render_template('error.html', error=error_message), 404

Handling API Errors

For API endpoints, you might want to return JSON responses instead of HTML templates. Here's how to implement that:


from flask import jsonify

@app.errorhandler(404)
def not_found_error(error):
    if request.accept_mimetypes.accept_json and \
       not request.accept_mimetypes.accept_html:
        return jsonify({'error': 'Not found'}), 404
    return render_template('404.html'), 404

Best Practices

Always include appropriate status codes with your error responses. This helps both users and machines understand the nature of the error.

Use Flask flash messages to provide additional feedback when redirecting users from error pages.

Conclusion

The app.errorhandler() is a powerful feature in Flask that helps you manage errors professionally. By implementing custom error pages, you can maintain a consistent user experience even when things go wrong.