You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask异常处理与消息闪现:实现友好错误页面展示

解决Flask错误页面优化问题

嘿,我来帮你搞定这个Flask错误展示的问题!你现在遇到的是debug模式下默认的丑陋回溯页面,想要换成更友好的展示方式,有两个实用方案可以选,下面一步步给你讲:


方案1:在math.html页面内直接显示错误提示

这个方案适合不想让用户跳转页面的场景,我们可以在路由里捕获异常,把错误信息传给模板,让模板根据有没有错误来展示不同内容。

修改后的Flask应用代码

from flask import Flask, render_template, request
server = Flask(__name__)

def add_stuff(x,y):
    if isinstance(x, int) and isinstance(y, int):
        z = x + y
        return z
    else:
        raise ValueError("Not integers")

@server.route('/math')
def foo():
    # 这里我假设你实际是从请求参数获取数值(原代码硬编码int不会触发错误)
    try:
        a = int(request.args.get('a', 1))  # 默认值1,也可以改成必填
        b = int(request.args.get('b', 15))
        out = add_stuff(a,b)
        error = None
    except ValueError as e:
        out = None
        error = str(e)
    return render_template('math.html', out=out, error=error)

if __name__ == '__main__':
    server.run(debug=True)

修改后的math.html模板

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Math Calculator</title>
<style>
/* 加一点简单样式让错误提示更显眼 */
.error {
    color: #dc3545;
    padding: 10px;
    border: 1px solid #dc3545;
    border-radius: 4px;
    margin: 10px 0;
}
.result {
    font-size: 1.2em;
    margin: 10px 0;
}
</style>
</head>
<body>
<h1>Math Addition</h1>
<!-- 如果有错误就显示错误信息,否则显示计算结果 -->
{% if error %}
    <div class="error">⚠️ {{ error }}</div>
{% elif out %}
    <div class="result">计算结果:{{ out }}</div>
{% endif %}
</body>
</html>

这样一来,当用户输入非整数参数(比如访问/math?a=5&b=abc),页面就会在原位置显示红色的错误提示,而不是跳转到回溯页面。


方案2:跳转到自定义美观错误页面

如果你希望错误发生时跳转到一个专门的错误页面,可以用Flask的errorhandler装饰器来捕获特定异常,返回自定义的错误页面。

修改后的Flask应用代码

from flask import Flask, render_template, request
server = Flask(__name__)

def add_stuff(x,y):
    if isinstance(x, int) and isinstance(y, int):
        z = x + y
        return z
    else:
        raise ValueError("Not integers")

@server.route('/math')
def foo():
    a = int(request.args.get('a', 1))
    b = int(request.args.get('b', 15))
    out = add_stuff(a,b)
    return render_template('math.html', out=out)

# 捕获ValueError异常,返回自定义错误页面
@server.errorhandler(ValueError)
def handle_value_error(e):
    return render_template('error.html', error_msg=str(e)), 400  # 400表示客户端错误

# 可选:捕获通用的500服务器错误
@server.errorhandler(500)
def internal_error(e):
    return render_template('error.html', error_msg="服务器内部错误"), 500

if __name__ == '__main__':
    # 注意:debug模式下Flask会优先显示调试页面,测试自定义错误页面时可以暂时关闭debug
    server.run(debug=False)

自定义错误页面error.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>出错啦!</title>
<style>
.container {
    max-width: 600px;
    margin: 100px auto;
    text-align: center;
    font-family: Arial, sans-serif;
}
.error-icon {
    font-size: 4em;
    color: #dc3545;
}
.error-msg {
    font-size: 1.2em;
    margin: 20px 0;
    color: #333;
}
.back-link {
    display: inline-block;
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    text-decoration: none;
    border-radius: 4px;
}
.back-link:hover {
    background-color: #0056b3;
}
</style>
</head>
<body>
<div class="container">
    <div class="error-icon">❌</div>
    <h2>哎呀,出错了</h2>
    <div class="error-msg">{{ error_msg }}</div>
    <a href="/math" class="back-link">返回计算页面</a>
</div>
</body>
</html>

这个方案会在触发错误时跳转到一个样式美观的错误页面,没有任何回溯信息,适合生产环境使用。记得生产环境一定要关闭debug模式,否则自定义错误页面不会生效。


内容的提问来源于stack exchange,提问作者user350540

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:22:45