为什么在我的单页应用程序中获取错误没有堆栈跟踪?

1 javascript error-handling stack-trace reactjs fetch-api

我有两个简单的包装器来处理我的单页应用程序中的请求。如果响应不正确(不在 200-300 范围内),则包装fetch并抛出错误:

const fetchy = (...args) =>
  fetch(...args).then(response => {
    if (response.ok) {
      return response
    }

    throw new Error(response.statusText)
  })

export default fetchy
Run Code Online (Sandbox Code Playgroud)

一个包装 fetchy 并用于 GET 请求:

const get = endpoint => {
  const headers = new Headers({ Authorization: `Bearer ${TOKEN}` })
  const init = { method: 'GET', headers }

  return fetchy(endpoint, init)
}
Run Code Online (Sandbox Code Playgroud)

现在我在这样的动作中使用它们(这是一个redux-thunk动作创建者):

export const fetchArticles = () => dispatch => {
  dispatch({ type: types.FETCH_ARTICLES })

  return get(endpoints.ARTICLES)
    .then(response => response.json())
    .then(data => normalize(data.items, [schemas.articles]))
    .then(normalized => dispatch(fetchArticlesSuccess(normalized)))
    // fetch errors caught here do not have error.stack
    .catch(error => dispatch(fetchArticlesFail(error)))
}
Run Code Online (Sandbox Code Playgroud)

因此,我捕获了 fetch 本身的错误(网络错误)和fetchy包装器返回的错误(api 错误)。问题是 fetchArticles 中捕获的 fetch 网络错误不包含堆栈跟踪。所以error.stack不存在。这弄乱了我的错误报告。

这是一个有效的错误,并且error instanceof Error === trueerror.message === 'Failed to fetch'。那么为什么这个错误没有堆栈跟踪呢?我该如何解决?似乎我可以向 fetchy 添加一个错误回调并在那里重新抛出任何错误,但这对我来说似乎很奇怪(但也许我错了)。

Jaf*_*ake 5

fetch 错误是异步创建的,与 JavaScript 的特定行没有直接关系。虽然我同意如果包含 fetch 调用的行会有所帮助。我已经为此提交了一个错误https://bugs.chromium.org/p/chromium/issues/detail?id=718760

作为一种解决方法,您可以捕获 fetch 错误,并在堆栈中没有数字时抛出一个新错误:

function fetchy(...args) {
  return fetch(...args).catch(err => {
    if (!err.stack.match(/\d/)) throw TypeError(err.message);
    throw err;
  }).then(response => {
    if (response.ok) return response;
    throw Error(response.statusText);
  });
}
Run Code Online (Sandbox Code Playgroud)

这是运行http://jsbin.com/qijabi/edit?js,console的示例


小智 5



\n最近我遇到了同样的错误。生产渠道在短短 2 个月内就记录了大约 500 次此错误,这确实令人恼火。我们的\xe2\x80\x99 是一个 Rails 应用程序,前端由 React 提供支持。

\n\n

这就是我们案例中发生的情况。当页面加载时,刷新按钮更改为十字按钮,现在如果在此页面加载时间内正在进行某些 api 请求并且用户单击此十字按钮,则 chrome 浏览器会抛出此错误。对于同样的情况,Firefox 在尝试获取资源时会抛出 NetworkError。这实际上并不是我们应该担心的问题,因此我们决定使用sentry 的ignoreErrors 属性来让sentry 忽略此错误。

\n\n
Sentry.init({\n  dsn: "sentry_dsn",\n  ignoreErrors: [\n    \'TypeError: Failed to fetch\',\n    \'TypeError: NetworkError when attempting to fetch resource.\'\n  ],\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n


\n注意:
\n无法获取也是由CORS错误生成的,请也注意这一点。\n此外,我们决定使用哨兵的 beforeSend 回调忽略 statusCode 在 400 到 426 之间的错误。

\n\n

我花了几天时间试图找到这个错误。希望这对某人有帮助。

\n\n

最初我在此页面上写了此回复 - https://forum.sentry.io/t/typeerror-failed-to-fetch-reported-over-and-overe/8447/2

\n\n

谢谢

\n