Javascript Axios 处理错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/49967779/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Axios handling errors
提问by mignz
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().
我正在尝试使用 Axios 更好地理解 javascript 承诺。我假装是处理 Request.js 中的所有错误,并且只从任何地方调用请求函数而不必使用catch().
In this example, the response to the request will be 400 with an error message in JSON.
在此示例中,对请求的响应将为 400,并带有 JSON 格式的错误消息。
This is the error I'm getting:
这是我得到的错误:
Uncaught (in promise) Error: Request failed with status code 400
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?
我找到的唯一解决方案是添加.catch(() => {})Somewhere.js,但我试图避免这样做。是否可以?
Here's the code:
这是代码:
Request.js
请求.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
某处.js
export default class Somewhere extends React.Component {
  ...
  callSomeRequest() {
    request('DELETE', '/some/request').then(
      () => {
        console.log('Request successful!')
      }
    )
  }
  ...
}
回答by Plabon Dutta
Actually, it's not possible with axios as of now. The status codes which falls in the range of 2xxonly, can be caught in .then().
实际上,目前使用 axios 是不可能的。处于2xxonly范围内的状态代码可以在.then().
A conventional approach is to catch errors in the catch()block like below:
传统的方法是在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);
    }
  });
Another approach can be intercepting requests or responses before they are handled by then or catch.
另一种方法是在它们被 then 或 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);
  });
回答by elonaire
If you want to gain access to the whole the error body, do it as shown below:
如果您想访问整个错误正文,请按如下所示操作:
 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;
  }
}
回答by Md.Abdul Halim Rafi
You can go like this: 
 error.response.data
In my case, I got errorproperty from backend. So, I used error.response.data.error
你可以这样: 
  error.response.data
在我的例子中,我从后端得到了error属性。所以,我使用了error.response.data.error
My code:
我的代码:
axios
     .get(`${API_BASE_URL}/students`)
     .then(response => {
        return response.data
      })
     .then(data => {
        console.log(data)
     .catch(error => {
       console.log(error.response.data.error)
      })
回答by user4920718
if u wanna use async await try
如果你想使用异步等待尝试
export const post = async ( link,data ) => {
const option = {
    method: 'post',
    url: `${URL}${link}`,
    validateStatus: function (status) {
        return status >= 200 && status < 300; // default
      },
    data
};
try {
    const response = await axios(option);
} catch (error) {
    const { response } = error;
    const { request, ...errorObject } = response; // take everything but 'request'
    console.log(response);
}
 };
回答by David Schumann
call the request function from anywhere without having to use catch().
从任何地方调用请求函数而不必使用 catch()。
First, while handling most errors in one place is a good Idea, it's not that easy with requests. Some errors (e.g. 400 validation errors like: "username taken" or "invalid email") should be passed on.
首先,虽然在一个地方处理大多数错误是一个好主意,但处理请求并不容易。一些错误(例如 400 验证错误,如:“用户名被占用”或“电子邮件无效”)应该被传递。
So we now use a Promise based function:
所以我们现在使用一个基于 Promise 的函数:
const baseRequest = async (method: string, url: string, data: ?{}) =>
  new Promise<{ data: any }>((resolve, reject) => {
    const requestConfig: any = {
      method,
      data,
      timeout: 10000,
      url,
      headers: {},
    };
    try {
      const response = await axios(requestConfig);
      // Request Succeeded!
      resolve(response);
    } catch (error) {
      // Request Failed!
      if (error.response) {
        // Request made and server responded
        reject(response);
      } else if (error.request) {
        // The request was made but no response was received
        reject(response);
      } else {
        // Something happened in setting up the request that triggered an Error
        reject(response);
      }
    }
  };
you can then use the request like
然后你可以像这样使用请求
try {
  response = await baseRequest('GET', 'https://myApi.com/path/to/endpoint')
} catch (error) {
  // either handle errors or don't
}

