0
0
FlaskDebug / FixBeginner · 4 min read

How to Handle Errors in Flask: Simple Guide with Examples

In Flask, you handle errors by defining errorhandler functions for specific HTTP error codes or exceptions, which lets you customize the response when errors occur. You can also use try-except blocks inside your routes to catch and manage exceptions directly.
🔍

Why This Happens

Errors in Flask happen when your app encounters unexpected situations like missing pages or server problems. Without handling, Flask shows a default error page or a traceback, which is not user-friendly.

python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    # This will cause a ZeroDivisionError
    result = 1 / 0
    return f'Result is {result}'

if __name__ == '__main__':
    app.run(debug=True)
Output
Traceback (most recent call last): File "app.py", line 7, in home result = 1 / 0 ZeroDivisionError: division by zero During handling of the above exception, another error occurred: Internal Server Error
🔧

The Fix

Use Flask's @app.errorhandler decorator to catch specific errors and return friendly messages. Also, use try-except inside routes to handle exceptions gracefully.

python
from flask import Flask, render_template_string

app = Flask(__name__)

@app.errorhandler(404)
def page_not_found(e):
    return render_template_string('<h1>Page not found</h1><p>Sorry, this page does not exist.</p>'), 404

@app.route('/')
def home():
    try:
        result = 1 / 0
        return f'Result is {result}'
    except ZeroDivisionError:
        return '<h1>Error</h1><p>Cannot divide by zero.</p>', 500

if __name__ == '__main__':
    app.run(debug=True)
Output
When visiting '/', the page shows: <h1>Error</h1><p>Cannot divide by zero.</p> When visiting a non-existent page, the page shows: <h1>Page not found</h1><p>Sorry, this page does not exist.</p>
🛡️

Prevention

Always anticipate possible errors by using try-except blocks in your routes and define error handlers for common HTTP errors like 404 and 500. Use logging to record errors for debugging and keep your app stable.

  • Use @app.errorhandler for HTTP errors.
  • Catch exceptions inside routes with try-except.
  • Log errors to understand issues.
  • Test your app to find edge cases.
⚠️

Related Errors

Other common errors include:

  • 500 Internal Server Error: Use error handlers to show friendly messages.
  • KeyError or TypeError: Catch these in try-except blocks to avoid crashes.
  • TemplateNotFound: Handle missing templates gracefully.

Key Takeaways

Use @app.errorhandler to create custom error pages for HTTP errors.
Wrap risky code in try-except blocks inside routes to catch exceptions.
Provide user-friendly messages instead of default error pages.
Log errors to help diagnose and fix issues quickly.
Test your app to catch errors before users do.