Axios 处理错误 [英] Axios handling errors

查看:45
本文介绍了Axios 处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我得到的错误:

未捕获(承诺)错误:请求失败,状态码为 400

我找到的唯一解决方案是在 Somewhere.js 中添加 .catch(() => {}) 但我试图避免这样做.可能吗?

代码如下:

<块引用>

请求.js

导出函数请求(方法,uri,body,headers){让配置 = {方法:method.toLowerCase(),网址:uri,baseURL: API_URL,标头:{'授权':'承载'+ getToken()},验证状态:函数(状态){返回状态 >= 200 &&状态<400}}...返回 axios(config).then(功能(响应){返回 response.data}).抓住(功能(错误){console.log('显示错误通知!')返回 Promise.reject(error)})}

<块引用>

Somewhere.js

export default class Somewhere extends React.Component {...callSomeRequest() {request('DELETE', '/some/request').then(() =>{console.log('请求成功!')})}...}

解决方案

实际上,目前无法使用 axios.仅在2xx范围内的状态码,可以在.then()中捕获.

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

axios.get('/api/xyz/abcd').catch(函数(错误){如果(错误.响应){//发出请求,服务器响应控制台日志(错误.响应数据);console.log(error.response.status);console.log(error.response.headers);} else if (error.request) {//请求已发出,但未收到响应控制台日志(错误.请求);} 别的 {//设置触发错误的请求时发生了一些事情console.log('错误', error.message);}});

另一种方法是在请求或响应被 then 或 catch 处理之前拦截它们.

axios.interceptors.request.use(function (config) {//在发送请求之前做一些事情返回配置;}, 函数(错误){//做一些请求错误的事情返回 Promise.reject(error);});//添加响应拦截器axios.interceptors.response.use(函数(响应){//对响应数据做一些事情返回响应;}, 函数(错误){//做一些有响应错误的事情返回 Promise.reject(error);});

I'm trying to understand javascript promises better with Axios. What I pretend is to handle all errors in Request.js and only call the request function from anywhere without having to use catch().

In this example, the response to the request will be 400 with an error message in JSON.

This is the error I'm getting:

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

The only solution I find is to add .catch(() => {}) in Somewhere.js but I'm trying to avoid having to do that. Is it possible?

Here's the code:

Request.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)
    }
  )
}

Somewhere.js

export default class Somewhere extends React.Component {

  ...

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

  ...

}

解决方案

Actually, it's not possible with axios as of now. The status codes which falls in the range of 2xx only, can be caught in .then().

A conventional approach is to catch errors in the catch() block like below:

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);
    }

  });

Another approach can be intercepting requests or responses before they are handled by then or catch.

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);
  });

这篇关于Axios 处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆