2
votes

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?

1

1 Answers

0
votes

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.

Since res.status > 200 will immediately throw an Error in Promise.then, so we need to something in catch.

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

  1. error.name
  2. error.message

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error