【问题标题】:What to use instead of window.onunhandledrejection to handle promise errors in different browsers?用什么代替 window.onunhandledrejection 来处理不同浏览器中的 promise 错误?
【发布时间】:2018-11-07 00:02:33
【问题描述】:

我正在尝试创建记录器来处理客户端上的错误并将它们发送到服务器。处理 Promise 中的错误的最佳方法是什么(在 .then 中)?

我正在使用此代码,它仅在 CHROME 中或多或少可以正常工作

window.onunhandledrejection = function(e) {
    if (e && e.detail && e.detail.reason) {
        this.sendErrorDetails('error', e.detail.reason.message)
    }
}

它应该是单独的logger.js文件,它会自动捕获所有的错误。

【问题讨论】:

  • 你说得对,确实是only works in Chrome
  • @JessedeBruijne 所以没有其他方法可以作为跨浏览器解决方案吗?
  • 还有其他方法,但它们很可能会处理覆盖本机方法。例如,将 Promise 替换为自定义函数,该函数将在内部使用原始原生承诺,并在需要时继续附加新的捕获/拒绝调用。
  • 您可以使用像 bluebird 这样的 Promise 库来触发这些事件。
  • 我不知道 Firefox 还没有它——我记得他们实现了它——我们已经为 Node.js 和 Chrome 拥有它 3 年了。我会看看我能不能找到负责的人并说服他们这很重要:)

标签: javascript logging promise


【解决方案1】:

unhandledrejection 似乎是唯一的解决方案,只有Chrome and Safari has supported it(2018 年 10 月)。

或者,您可以改用axios,通过它您可以使用响应拦截器作为全局错误处理程序,查看:

这里是来自axios 的自述文件的代码 sn-p 的副本,以方便参考:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

【讨论】:

    猜你喜欢
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多