Axios 处理错误

2022-08-30 00:21:48

我试图用Axios更好地理解javascript的承诺。我假装的是处理 Request 中的所有错误.js并且仅从任何地方调用 request 函数,而不必使用 。catch()

在此示例中,对请求的响应将为 400,并显示 JSON 格式的错误消息。

这是我得到的错误:

Uncaught (in promise) Error: Request failed with status code 400

我发现的唯一解决方案是添加某个地方.js但我试图避免这样做。可能吗?.catch(() => {})

代码如下:

请求.js

export function request(method, uri, body, headers) {
  let config = {
    method: method.toLowerCase(),
    url: uri,
    baseURL: API_URL,
    headers: { 'Authorization': 'Bearer ' + getToken() },
    validateStatus: function (status) {
      return status >= 200 && status < 400
    }
  }

  ...

  return axios(config).then(
    function (response) {
      return response.data
    }
  ).catch(
    function (error) {
      console.log('Show error notification!')
      return Promise.reject(error)
    }
  )
}

某处.js

export default class Somewhere extends React.Component {

  ...

  callSomeRequest() {
    request('DELETE', '/some/request').then(
      () => {
        console.log('Request successful!')
      }
    )
  }

  ...

}

答案 1

实际上,到目前为止,axios是不可能的。仅属于 范围内的状态代码可以在 中捕获。2xx.then()

传统的方法是捕获块中的错误,如下所示:catch()

axios.get('/api/xyz/abcd')
  .catch(function (error) {
    if (error.response) {
      // Request made and server responded
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }

  });

另一种方法可能是在处理请求或响应之前拦截它们或捕获。

axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

答案 2

如果要访问整个错误正文,请按如下所示进行操作:

 async function login(reqBody) {
  try {
    let res = await Axios({
      method: 'post',
      url: 'https://myApi.com/path/to/endpoint',
      data: reqBody
    });

    let data = res.data;
    return data;
  } catch (error) {
    console.log(error.response); // this is the main part. Use the response property from the error object

    return error.response;
  }

}