7. Error Handler

In Flask, an error handler is a component that allows you to define custom behavior for handling different types of errors that may occur in your application. This can be especially useful for providing user-friendly error messages, logging errors, or performing specific actions when certain errors occur.

Basic Usage of Error Handlers

To create an error handler in Flask, you can use the @app.errorhandler() decorator. This decorator is used to associate a specific error code (such as 404 for "Not Found" or 500 for "Internal Server Error") with a function that will handle that error.

Example

Here's an example of how you can use error handlers in a Flask application:

from flask import Flask, render_template

app = Flask(__name__)

# Example route that triggers an error
@app.route('/trigger-error')
def trigger_error():
    abort(404)  # This will trigger a 404 Not Found error

# Error handler for 404 Not Found
@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 404

# Error handler for 500 Internal Server Error
@app.errorhandler(500)
def internal_error(error):
    return render_template('500.html'), 500

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

Explanation

  • Route that triggers an error: In this example, the /trigger-error route intentionally triggers a 404 Not Found error by calling abort(404).

  • 404 Error Handler: The @app.errorhandler(404) decorator defines a function not_found_error that handles 404 errors. When a 404 error occurs, this function will render a custom 404.html template and return a 404 status code.

  • 500 Error Handler: Similarly, the @app.errorhandler(500) decorator defines a function internal_error that handles 500 errors. This function will render a custom 500.html template and return a 500 status code.

Custom Error Pages

To provide a user-friendly experience, you can create custom error pages (like 404.html and 500.html) that inform users about the error in a more user-friendly way than the default error pages. Here's a simple example of what a 404.html template might look like:

Conclusion

By using error handlers, you can ensure that your Flask application handles errors gracefully and provides meaningful feedback to users. This enhances the user experience and helps you manage errors more effectively.

Last updated