为什么Fetch错误在我的单页应用程序中没有stackTrace



我有两个简单的包装器,可以在我的单页应用程序中处理请求。如果响应不正常(不在200-300范围内(,则包裹fetch并引发错误:

const fetchy = (...args) =>
  fetch(...args).then(response => {
    if (response.ok) {
      return response
    }
    throw new Error(response.statusText)
  })
export default fetchy

一个包装Fetchy,用于获取请求:

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

现在我在这样的动作中使用它们(这是一个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)))
}

因此,我正在捕获两个错误(网络错误(中的两个错误,并且从fetchy包装器(API错误(返回错误。问题在于,捕获在fetcharticles中的网络错误不包含堆栈跟踪。因此error.stack不存在。这搞砸了我的错误报告。

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

fetch误差是异步创建的&与特定的JavaScript行不直接相关。尽管我同意,如果包含获取电话的线路,这将是有帮助的。我已经为此提交了一个错误

作为解决方法,如果堆栈中没有数字:

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);
  });
}

以下是运行http://jsbin.com/qijabi/edit?js,console

的示例



最近,我面临着同样的错误。生产频道在短短2个月内记录了大约500次此错误,这确实令人烦恼。我们的'是一个由React提供动力的前端的铁轨应用程序。

这是我们案件中发生的事情。当页面加载时,刷新按钮更改为交叉按钮,现在,如果在此页面加载时间内进行了一些API请求,并且用户单击此交叉按钮,则Chrome浏览器会丢弃此错误。对于同样的情况,Firefox在尝试获取资源时会引发NetworkError。这并不是我们应该担心的问题,因此我们决定通过使用Sentry的ignoreErrors属性使Sentry忽略此错误。

Sentry.init({
  dsn: "sentry_dsn",
  ignoreErrors: [
    'TypeError: Failed to fetch',
    'TypeError: NetworkError when attempting to fetch resource.'
  ],
});


注意:
cors 错误也无法获取,也请注意这一点。此外,我们决定使用Sentry的Beforesend回调在400至426之间忽略错误代码。

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

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

谢谢

最新更新