Flask错误处理 #

一、错误处理概述 #

1.1 错误类型 #

类型 说明
HTTP错误 404、500等
应用错误 业务逻辑错误
数据库错误 数据库操作错误

二、自定义错误页面 #

2.1 使用errorhandler #

python
from flask import render_template

@app.errorhandler(404)
def page_not_found(e):
    return render_template('errors/404.html'), 404

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('errors/500.html'), 500

@app.errorhandler(403)
def forbidden(e):
    return render_template('errors/403.html'), 403

2.2 错误模板 #

templates/errors/404.html:

html
{% extends "base.html" %}

{% block title %}页面不存在{% endblock %}

{% block content %}
<h1>404 - 页面不存在</h1>
<p>您访问的页面不存在</p>
<a href="{{ url_for('main.index') }}">返回首页</a>
{% endblock %}

三、API错误响应 #

3.1 JSON错误响应 #

python
from flask import jsonify

@app.errorhandler(404)
def api_not_found(e):
    return jsonify({'error': '资源不存在', 'code': 404}), 404

@app.errorhandler(400)
def bad_request(e):
    return jsonify({'error': '请求参数错误', 'code': 400}), 400

四、下一步 #

接下来让我们学习 日志系统,了解Flask日志配置!

最后更新:2026-03-28