【发布时间】:2017-10-03 16:51:38
【问题描述】:
我有两个简单的包装器来处理我的单页应用程序中的请求。如果响应不正确(不在 200-300 范围内),则包装 fetch 并引发错误:
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 === true 和 error.message === 'Failed to fetch'。那么为什么这个错误没有堆栈跟踪呢?我该如何解决?似乎我可以为 fetchy 添加一个错误回调并在那里重新抛出任何错误,但这对我来说似乎很奇怪(但也许我错了)。
【问题讨论】:
-
显然 error.stack 是非标准的:developer.mozilla.org/en/docs/Web/JavaScript/Reference/…。但是,由于错误是在支持 error.stack 的浏览器(Chrome 57)中引发的,因此 fetch 没有堆栈跟踪似乎很奇怪。是不是使用同一个Error构造函数?
标签: javascript reactjs error-handling stack-trace fetch-api