gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:42:08 25 4
gpt4 key购买 nike

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

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

throw new Error(response.statusText)
})

export default fetchy

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

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

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

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

最佳答案

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

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

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 的示例

关于javascript - 为什么在我的单页应用程序中获取错误没有堆栈跟踪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43800998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com