0
0
Flaskframework~5 mins

Error handling in production in Flask

Choose your learning style9 modes available
Introduction

Error handling in production helps your app stay stable and show friendly messages when something goes wrong.

When your Flask app faces unexpected errors from users or servers.
When you want to log errors for later fixing without crashing the app.
When you want to show simple, clear error pages instead of confusing technical details.
When you want to handle specific errors like 404 (page not found) or 500 (server error).
Syntax
Flask
from flask import Flask, render_template

app = Flask(__name__)

@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

Use @app.errorhandler(code) to catch specific HTTP errors.

Return a response and the error code to show a custom error page.

Examples
Shows a simple text message for 404 errors.
Flask
from flask import Flask

app = Flask(__name__)

@app.errorhandler(404)
def page_not_found(e):
    return 'Page not found!', 404
Returns a JSON response for 500 errors, useful for APIs.
Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.errorhandler(500)
def server_error(e):
    return jsonify(error='Server error, try later'), 500
Catches all exceptions and shows a generic error message.
Flask
from flask import Flask

app = Flask(__name__)

@app.errorhandler(Exception)
def handle_all_errors(e):
    return 'Something went wrong!', 500
Sample Program

This Flask app shows custom messages for 404 and 500 errors. The /cause-error route triggers a server error to test the 500 handler.

Flask
from flask import Flask, render_template_string

app = Flask(__name__)

# Custom 404 error page
@app.errorhandler(404)
def not_found(e):
    return render_template_string('<h1>404 Not Found</h1><p>Sorry, this page does not exist.</p>'), 404

# Custom 500 error page
@app.errorhandler(500)
def internal_error(e):
    return render_template_string('<h1>500 Internal Server Error</h1><p>Oops! Something went wrong.</p>'), 500

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

@app.route('/cause-error')
def cause_error():
    1 / 0  # This will cause a ZeroDivisionError

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

Set debug=False in production to avoid showing detailed error info to users.

Use logging inside error handlers to record errors for fixing later.

Custom error pages improve user experience and keep your app professional.

Summary

Error handling keeps your app stable and user-friendly.

Use @app.errorhandler to catch and respond to errors.

Show simple, clear messages instead of raw error details in production.