首页 > 解决方案 > 在 fetch 调用中使用响应正文引发自定义错误

问题描述

我想知道如何创建自定义错误处理,我将在其中获取已解析的响应主体并将其传递给 fetch 函数中的自定义错误。在我的示例中,我收到响应正文中许多字段的验证错误。这是一个例子:

class ValidationError extends Error {
  constructor(resBody, ...params) {
    super(...params);

    this.name = 'ValidationError';
    this.body = resBody.json();
  }
}

这是 fetch 函数:

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。我该如何解决这个问题,以便我可以error types根据response status我的fetch功能设置不同的,我可以在哪里使用resolved response body

标签: javascripterror-handlingfetch

解决方案


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

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

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

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

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

  1. 错误名称
  2. 错误信息

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


推荐阅读