【问题标题】:Throw a custom error with response body in fetch call在 fetch 调用中使用响应正文引发自定义错误
【发布时间】: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


    【解决方案1】:

    回复晚了。但希望它可以帮助其他搜索相同问题的人。

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

    由于 res.status > 200 会立即在 Promise.then 中抛出一个错误,所以我们需要在 catch 中添加一些东西。

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

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

    1. error.name
    2. 错误信息

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      • 2015-03-10
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多