Axios处理错误 [英] Axios handling errors
问题描述
我试图用Axios更好地理解javascript Promise.我假装是处理Request.js中的所有错误,并且仅从任何地方调用请求函数,而不必使用catch()
.
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()
.
在此示例中,对请求的响应将为400,并带有JSON错误消息.
In this example, the response to the request will be 400 with an error message in JSON.
这是我得到的错误:
Uncaught (in promise) Error: Request failed with status code 400
我找到的唯一解决方案是在Somewhere.js中添加.catch(() => {})
,但是我试图避免这样做.有可能吗?
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?
代码如下:
Request.js
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
Somewhere.js
export default class Somewhere extends React.Component {
...
callSomeRequest() {
request('DELETE', '/some/request').then(
() => {
console.log('Request successful!')
}
)
}
...
}
推荐答案
实际上,到目前为止,axios无法实现.只能在2xx
范围内的状态代码可以捕获在.then()
中.
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()
.
常规方法是在catch()
块中捕获错误,如下所示:
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屋!