【发布时间】:2019-08-29 16:37:28
【问题描述】:
我想知道如何创建自定义错误处理,在其中获取已解析的响应正文并将其传递给 fetch 函数中的自定义错误。 在我的示例中,我收到响应正文中许多字段的验证错误。这是一个例子:
class ValidationError extends Error {
constructor(resBody, ...params) {
super(...params);
this.name = 'ValidationError';
this.body = resBody.json();
}
}
这是获取函数:
return fetch(
`${this.formUrl(id)}/status`,
{
method: 'PATCH',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(jsonBody)
})
.then((res) => {
if (res.ok) {
return res.json();
}
if (res.status === 400) {
throw new ValidationError(res.body);
} else {
throw new Error(`http failed: ${res.status} ${res.statusText}`);
}
});
然后我在我的组件中使用它:
.then(() => {
this.setState({navigateTo: '/'})
}).catch(error => {
this.setState({error});
})
但是,这失败了,因为 res.body 在那时是 readableStream。我该如何解决这个问题,以便我可以在 fetch 函数中基于 response status 设置不同的 error types,我可以在其中使用 resolved response body?
【问题讨论】:
标签: javascript error-handling fetch