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

如何通过客户端回调在Dash应用中捕获并展示浏览器控制台错误?

解决Dash应用中客户端捕获浏览器错误并展示的问题

现有代码的问题分析

  • 布局中错误存储容器的ID与客户端回调的Input不匹配:布局里是error-handler,但回调里用了error-store
  • Output目标组件未正确引用:usernotification未定义,应该使用'user_notification'
  • 错误存储容器类型不合适:用html.Div存储错误信息,Dash的Input回调无法监听其textContent变化,应该改用html.Input(支持value属性)
  • 客户端脚本触发的事件不匹配:Div的input事件无法被Dash正确捕获,改用Input组件的change事件更可靠

修正后的完整代码

1. 修正app.py代码

from dash import Dash, html, Output, Input, clientside_callback

app = Dash(__name__, external_scripts=[{'src': '/assets/error.js'}])  # 引入外部脚本

app.layout = html.Div([
    # 改用Input作为错误存储容器,隐藏显示
    html.Input(id='error-handler', style={'display': 'none'}, type='text'),
    html.Div(id='user_notification', style={'color': 'red', 'margin-top': '10px'})
])

clientside_callback(
    """
    function(errorMessage) {
        console.log('捕获到错误:', errorMessage);
        return errorMessage;
    }
    """,
    Output('user_notification', 'children'),
    Input('error-handler', 'value')  # 匹配布局中的ID
)

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

2. 修正error.js代码(放在项目的assets目录下,Dash会自动加载)

const originalFetch = window.fetch;
window.fetch = function() {
    return originalFetch.apply(this, arguments)
        .then(response => {
            // 捕获所有HTTP错误状态码(4xx/5xx)
            if (!response.ok) {
                const errorMessage = `HTTP错误: ${response.status} ${response.statusText}`;
                sendErrorToDash(errorMessage);
            }
            return response;
        })
        .catch(error => {
            // 捕获网络错误(如服务器宕机、代理关闭)
            const errorMessage = `网络错误: ${error.message}`;
            sendErrorToDash(errorMessage);
            throw error;
        });
};

function sendErrorToDash(errorMessage) {
    const errorStore = document.querySelector('#error-handler');
    if (errorStore) {
        errorStore.value = errorMessage;  // 设置Input的value属性
        const event = new Event('change', { bubbles: true });
        errorStore.dispatchEvent(event);  // 触发change事件触发Dash回调
    }
}

关键修改说明

  • 错误存储容器:改用html.Input,因为Dash的Input回调会监听其value属性变化,而Div的textContent无法被Dash的Input组件回调捕获
  • 脚本加载:将error.js放在Dash项目的assets目录下,或通过external_scripts指定路径,确保脚本在页面加载时执行
  • 错误捕获范围:扩展了HTTP错误的捕获逻辑,通过response.ok判断所有4xx/5xx状态码,而不仅仅是403
  • 事件触发:改用change事件,确保Dash能正确捕获到值的变化

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:30:09