首页 > 解决方案 > 当响应返回适当的错误消息时处理 fetch 错误

问题描述

我有以下获取功能

request(url, options) {
  return fetch(url, _.defaultsDeep(options || {}, defaultOptions))
     .then(handleErrors)
     .then(response => response.json())
     .catch(error => handleFetchError(error));
}

handleErrors函数执行以下操作以检查响应是否失败...

function handleErrors(response) {
   if (!response.ok) {
      throw new Error(response.statusText);
   }
   return response;
}

我遇到的问题是 API 返回一个400状态,还有一个带有相关错误消息的数组,但使用throw new Error(response.statusText);只返回一些通用错误消息Error: [object Object],而不是访问错误数组。

这是我期望在响应中返回的

{
    "status": 400,
    "error": "Bad Request",
    "errors": [
                   { "defaultMessage": "Please check that your name contains only letters and is longer than two characters" }
              ]
}

我无权访问 API 服务器端,因此我无法在那里更改任何内容。

但是有没有一种方法可以让我抛出一个错误来捕获但也可以访问errors响应中的数组?

编辑:

handleErrors是我收到的响应对象

{
  "type": "default",
  "status": 401,
  "ok": false,
  "statusText": "",
  "headers": {
    "map": {
      "pragma": "no-cache",
      "date": "Wed, 01 May 2019 07:44:40 GMT",
      "x-content-type-options": "nosniff",
      "x-frame-options": "DENY",
      "content-type": "application/json;charset=ISO-8859-1",
      "cache-control": "no-cache, no-store, max-age=0, must-revalidate",
      "content-length": "53",
      "x-xss-protection": "1; mode=block",
      "expires": "0"
    }
  },
  "url": "http://localhost:8080/login",
  "_bodyInit": {},
  "_bodyBlob": {}
}

当我抛出错误并尝试在参数中访问它时handleFetchError只是error一个空对象{}

标签: javascriptreactjserror-handlingfetch

解决方案


看起来您正在尝试抛出response.statusText,但您的响应没有该属性。它有status.


推荐阅读