Throw a custom error with response body in fetch call

时间:2019-04-08 13:46:51

标签: javascript error-handling fetch

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 个答案:

答案 0 :(得分:0)

延迟答复。但是希望它可以帮助其他人搜索相同的问题。

我们需要检查 error.response.data ,以在catch块中获取已解决的 响应正文

由于res.status> 200会立即在Promise中引发一个错误,因此,我们需要注意一些问题。

.catch(error => {
    if (error.response.status === 400) {
      console.log(error.response.data)
    } else {
      .....
    }
  })

仍有一些方法可以获取错误内的详细信息。

  1. error.name
  2. error.message

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