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_templateapp =Flask(__name__)# Example route that triggers an error@app.route('/trigger-error')deftrigger_error():abort(404)# This will trigger a 404 Not Found error# Error handler for 404 Not Found@app.errorhandler(404)defnot_found_error(error):returnrender_template('404.html'),404# Error handler for 500 Internal Server Error@app.errorhandler(500)definternal_error(error):returnrender_template('500.html'),500if__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.
<!DOCTYPE html>
<html>
<head>
<title>Page Not Found</title>
</head>
<body>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
<a href="/">Go to Home</a>
</body>
</html>