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. 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. 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?