0
0
Flaskframework~5 mins

Error handler decorators in Flask

Choose your learning style9 modes available
Introduction

Error handler decorators help you catch and respond to errors in your web app in a simple way.

You want to show a friendly message when a user visits a page that does not exist.
You want to handle server errors and log them while showing a custom error page.
You want to return a specific response when a user sends a bad request.
You want to keep your app running smoothly by managing unexpected errors gracefully.
Syntax
Flask
@app.errorhandler(error_code_or_exception)
def function_name(error):
    # handle the error
    return response, status_code
Use the @app.errorhandler decorator with an error code like 404 or an exception class.
The decorated function receives the error object and returns a response and status code.
Examples
This handles 404 errors by returning a simple message and status code.
Flask
@app.errorhandler(404)
def page_not_found(error):
    return "Page not found", 404
This handles server errors with a custom message.
Flask
@app.errorhandler(500)
def server_error(error):
    return "Server error, try later", 500
This handles a specific exception type for bad requests.
Flask
from werkzeug.exceptions import BadRequest

@app.errorhandler(BadRequest)
def handle_bad_request(error):
    return "Bad request!", 400
Sample Program

This Flask app has two error handlers: one for 404 errors and one for 500 errors. When a user visits a page that does not exist, they see a friendly message. If the server has an error, they see a different message.

Flask
from flask import Flask

app = Flask(__name__)

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

@app.errorhandler(404)
def page_not_found(error):
    return "Sorry, this page does not exist.", 404

@app.errorhandler(500)
def server_error(error):
    return "Oops! Something went wrong on the server.", 500

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

Use error handler decorators to keep your app user-friendly and stable.

Remember to return both a message and the correct HTTP status code.

Testing your error handlers by visiting wrong URLs or causing errors helps ensure they work.

Summary

Error handler decorators catch errors and let you respond nicely.

Use @app.errorhandler with error codes or exceptions.

Return a message and status code to inform users clearly.