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

Flask API抛出错误时无响应,需返回除零错误信息

问题解决步骤

核心问题:缺少Flask应用实例初始化

你的代码没有创建Flask应用的核心实例,这会导致服务器无法正常启动,自然无法返回任何响应。必须添加以下关键代码:

app = Flask(__name__)  # 初始化Flask应用实例

同时,要启动本地测试服务器,需在代码末尾补充:

if __name__ == '__main__':
    app.run(debug=True)  # debug模式便于开发阶段排查问题

优化异常处理(可选但推荐)

你当前的代码中,每个函数都重复捕获异常并重新抛出ValueError,既冗余又会丢失原始异常的上下文信息。可以简化逻辑,让错误直接传递到路由处理函数统一处理:

修改后的完整可运行代码:

from flask import Flask, jsonify

app = Flask(__name__)

def first_function():
    second_function()

def second_function():
    print("second_function")
    third_function()
    print("I do not want to see this sentence.")

def third_function():
    print("third_function")
    print(1/0)

@app.route('/control', methods=['POST'])
def get():
    try:
        first_function()
        return jsonify({})
    except Exception as error:
        error_message = str(error).split("\n")[0]
        response = {"text" : f"Something went wrong when operating 'get' process. -> {error_message}"}
        print("Error on main function ", error_message)
        return jsonify(response), 400  # 返回400状态码明确标记客户端错误

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

验证效果

启动服务器后,向/control发送POST请求,你会收到包含除零错误信息的响应:

{"text": "Something went wrong when operating 'get' process. -> division by zero"}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:28:11