Flask Error Handling
Flask provides a flexible error-handling mechanism that can capture and handle various errors in an application.
Good error handling is not just about "no bugs", but also about giving users a friendly experience when bugs do occur.
This chapter covers how to customize error pages and manage logs in Flask.
Custom error pages
By default, Flask displays a simple black-and-white page for errors such as 404.
Use the @app.errorhandler decorator to customize error pages for specific HTTP status codes:
Example
from
flask
import
Flask
,
render_template
app
=
Flask
(
name
)
Handle 404 errors—page not found
@
app.
errorhandler
(
404
)
def
page_not_found
(
error
)
:
Note: you must explicitly return status code 404
return
render_template
(
"404.html"
)
,
404
Handle 500 errors—internal server error
@
app.
errorhandler
(
500
)
def
internal_error
(
error
)
:
return
render_template
(
"500.html"
)
,
500
Handle 403 errors—forbidden
@
app.
errorhandler
(
403
)
def
forbidden
(
error
)
:
return
render_template
(
"403.html"
)
,
403
The corresponding 404 template:
Example
404 - Page not found
404
Sorry, the page you requested does not exist.
in errorhandler In the decorated function,return the status code must be explicitly included. If you omit it , 404, Flask will return status code 200 by default, and browsers and search engines will not consider this an error page.
Exception class registration
Besides status codes, @app.errorhandler can also register exception classes directly:
Example
from
werkzeug.
exceptions
import
HTTPException
@
app.
errorhandler
(
HTTPException
)
def
handle_http_exception
(
error
)
:
"""Handle all HTTP exceptions uniformly (such as 400, 401, 403, 404, etc.)"""
return
f
"""
HTTP error {error.code}
{error.description}
Return to the RUNOOB home page
"""
,
error.
code
Triggering errors with abort
In your view functions, use abort() to actively trigger HTTP errors:
Example
from
flask
import
abort
Mock an article database
articles
=
{
1
:
{
"title"
:
"Flask Getting Started Tutorial"
}
,
2
:
{
"title"
:
"Python Basics"
}
,
}
@
app.
get
(
"/article/int:article_id"
)
def
view_article
(
article_id
)
:
article
=
articles.
get
(
article_id
)
if
article
is
None
:
If the article does not exist, return 404
The description argument is passed to the errorhandler
abort
(
404
,
description
=
f
"Article ID {article_id} does not exist"
)
return
f
"
{article['title']}
"@
app.
get
(
"/admin"
)
def
admin_panel
(
)
:
A user without admin privileges accesses the admin backend
abort
(
403
,
description
=
"You do not have administrator privileges"
)
Logging
Flask uses Python's standard library logging module; you can log through app.logger.
Logging is essential for troubleshooting—don't just use print(); logs provide richer context and better control.
Example
from
flask
import
Flask
,
request
app
=
Flask
(
name
)
@
app.
route
(
"/"
)
def
index
(
)
:
Different log levels
app.
logger
.
debug
(
"Visited the home page"
)
Debug information, usually not output in production
app.
logger
.
info
(
"User from IP: %s"
,
request.
remote_addr
)
Regular information
app.
logger
.
warning
(
"Detected abnormal access pattern"
)
Warning: needs attention but does not affect operation
app.
logger
.
error
(
"Database connection failed"
)
Error: functionality is affected
app.
logger
.
critical
(
"Insufficient disk space, service is about to stop"
)
Critical error: the service may stop
return
"OK"
Log levels (from low to high):
| Level | Use Cases |
|---|---|
| DEBUG | Detailed information for development and debugging, not output by default in production |
| INFO | General runtime information, such as request logs and service startup |
| WARNING | Warning messages, potential issues that do not affect current operation |
| ERROR | Error messages, when a feature fails but the service is still running |
| CRITICAL | Critical errors that may cause the service to stop |
In debug mode, Flask's log level is automatically set to DEBUG. In production, set it as needed to INFO or WARNING, to avoid outputting too much useless information.
Configure log output
Write logs to a file for later analysis and troubleshooting:
Example
import
logging
from
logging
.
handlers
import
RotatingFileHandler
Configure a file log handler—automatically rotate when the log file reaches 10MB
handler
=
RotatingFileHandler
(
"runoob_app.log"
,
Log file path
maxBytes
=
10
1024
1024
,
Maximum 10MB per single file
backupCount
=
5
Keep the most recent 5 backups
)
Set the log format
handler.
setFormatter
(
logging
.
Formatter
(
"[%(asctime)s] %(levelname)s in %(module)s: %(message)s"
)
)
Add the handler to Flask's logger
app.
logger
.
addHandler
(
handler
)
app.
logger
.
setLevel
(
logging
.
INFO
)
Catch unhandled exceptions
Using app.errorhandler(500), you can catch unhandled exceptions and log them:
Example
import
traceback
@
app.
errorhandler
(
500
)
def
internal_error
(
error
)
:
Log the complete exception stack trace
app.
logger
.
error
(
"Internal server error:\n%s"
,
traceback
.
format_exc
(
)
)
Show the user a friendly error page
return
"""
500 - Internal Server Error
Sorry, the server encountered an unexpected error. We have logged the issue; please try again later.
If the problem persists, please contact RUNOOB technical support.
"""
,
500
Common HTTP Error Codes Quick Reference
| Status code | Meaning | Common Causes |
|---|---|---|
| 400 | Bad Request | Malformed request parameters, missing required fields |
| 401 | Unauthorized | User not logged in or authentication failed |
| 403 | Forbidden | User is logged in but lacks access permission |
| 404 | Not Found | Resource (article, user, etc.) does not exist |
| 405 | Method Not Allowed | Wrong HTTP method used (e.g., using GET to access a POST endpoint) |
| 500 | Internal Server Error | Unhandled errors such as code exceptions or database connection failures |