0
0
Flaskframework~5 mins

Why error handling matters in Flask

Choose your learning style9 modes available
Introduction

Error handling helps your web app stay friendly and clear when things go wrong. It stops crashes and shows helpful messages instead.

When a user enters wrong data in a form
When a requested page or resource does not exist
When the server faces a problem processing a request
When external services or databases fail to respond
When you want to log errors for fixing bugs later
Syntax
Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.errorhandler(404)
def not_found(error):
    return jsonify({'error': 'Page not found'}), 404

@app.errorhandler(500)
def server_error(error):
    return jsonify({'error': 'Server error'}), 500

Use @app.errorhandler(code) to catch specific errors like 404 or 500.

Return a response with a helpful message and the error code.

Examples
This handles 404 errors by returning a JSON message.
Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.errorhandler(404)
def page_not_found(e):
    return jsonify({'error': 'This page does not exist'}), 404
This handles server errors with a friendly message.
Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.errorhandler(500)
def internal_error(e):
    return jsonify({'error': 'Oops! Something went wrong on the server.'}), 500
Sample Program

This Flask app has a homepage and a route that causes an error. It handles 404 and 500 errors by returning JSON messages instead of crashing.

Flask
from flask import Flask, jsonify

app = Flask(__name__)

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

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

@app.errorhandler(404)
def not_found(error):
    return jsonify({'error': 'Page not found'}), 404

@app.errorhandler(500)
def server_error(error):
    return jsonify({'error': 'Server error occurred'}), 500

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

Always handle common errors to improve user experience.

Use JSON responses for APIs and friendly HTML pages for websites.

Debug mode shows detailed errors but turn it off in production.

Summary

Error handling keeps your app stable and user-friendly.

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

Show clear messages so users know what happened.