捕获异常时如何获取 PythonFlask/React 应用程序的堆栈跟踪?

问题描述 投票:0回答:1

我正在使用 Flask/React 应用程序(openplayground),该应用程序无法正常工作(按网页上的提交按钮时,会打开一个错误对话框,其中显示消息:“只能将 str (不是“NoneType”)连接到斯特”

相同的消息被写入我使用启动应用程序的终端窗口中

python3 -m server.app --host 0.0.0.0 --port 5432

消息如下:

ERROR:server.lib.inference:Error: can only concatenate str (not "NoneType") to str

看起来python模块抛出了一个异常,该异常被捕获并且错误消息文本被传回前端。

但即使是终端窗口中的扩展消息对我来说也没有多大帮助,因为我无法找出错误发生的确切位置。理想情况下,我会获取完整的堆栈跟踪以找出发生异常的代码行号。

我该怎么做?有没有办法强制 python 解释器打印堆栈跟踪?或者我可以更改模块的代码以便打印跟踪吗?还有其他方法可以了解发生了什么吗?

编辑:

单击按钮后,Firefox 的开发者控制台会报告错误。我认为这与 python 解释器抛出的异常有关,也许它有帮助:

Firefox can’t establish a connection to the server at ws://a.b.c.d/1234

顺便说一句,基于 Debian 的虚拟机上的端口 1234 已打开,但根据 netstat 没有服务正在侦听。

python flask stack trace
1个回答
0
投票

您可以使用 Python 的回溯模块在 Flask 应用程序中全局捕获并记录异常的完整堆栈跟踪。

from flask import Flask
import traceback

app = Flask(__name__)

@app.route('/')
def index():
    # Your code here. This is just an example.
    return 'Hello, World!'

@app.errorhandler(Exception)
def handle_exception(e):
    # Pass the error to the HTTP error handler.
    stack_trace = traceback.format_exc()
    print(stack_trace)  # Or log it to a file or logging system
    return 'An error occurred, and we have logged the details. Please try again later.', 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5432)

此外,对于 WebSocket 连接问题,请确保服务已正确设置并侦听指定端口(1234)以处理 WebSocket 连接。

© www.soinside.com 2019 - 2024. All rights reserved.