[英]Throw a custom error with response body in fetch call
I would like to know how can I create a custom error handling where I would get the resolved response body and passed it to the custom error in fetch function.我想知道如何创建自定义错误处理,在其中获取已解析的响应正文并将其传递给 fetch 函数中的自定义错误。 In my example I getting a validation errors on many fields in response body.
在我的示例中,我在响应正文中的许多字段上收到验证错误。 This is the example:
这是示例:
class ValidationError extends Error {
constructor(resBody, ...params) {
super(...params);
this.name = 'ValidationError';
this.body = resBody.json();
}
}
And this is the fetch function:这是获取功能:
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}`);
}
});
Which I then use in my component:然后我在我的组件中使用它:
.then(() => {
this.setState({navigateTo: '/'})
}).catch(error => {
this.setState({error});
})
But, this fails since res.body
is the readableStream
at that point.但是,这失败了,因为
res.body
是当时的readableStream
。 How can I fix this so that I can set different error types
based on response status
in my fetch
function, where I would be able to use the resolved response body
?我该如何解决这个问题,以便我可以根据我的
fetch
函数中的response status
设置不同的error types
,在那里我可以使用resolved response body
?
A late reply.迟到的回复。 But hope it helps others searching for the same question.
但希望它可以帮助其他人搜索相同的问题。
We need to check error.response.data to get the resolved response body in catch block.我们需要检查error.response.data以在 catch 块中获取解析的响应体。
Since res.status > 200 will immediately throw an Error in Promise.then, so we need to something in catch.由于 res.status > 200 会立即在 Promise.then 中抛出一个错误,所以我们需要抓住一些东西。
.catch(error => {
if (error.response.status === 400) {
console.log(error.response.data)
} else {
.....
}
})
There are still some methods to get the details inside the error.仍然有一些方法可以获取错误内部的详细信息。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.