简介
Axios是一个JavaScript库,它使用Promise API来创建HTTP请求,在Node.js运行时使用http ,在浏览器使用XMLHttpRequests 。因为这些请求是承诺,所以它们可以使用较新的async/await语法,以及用于承诺链的.then() 函数和用于错误处理的.catch() 机制。
try {
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
// Handle error
console.log(err);
}
在这篇文章中,我们将看到如何用Axios处理错误,因为在进行任何HTTP调用时,这一点非常重要,因为你完全知道有时你所调用的服务可能无法使用或返回其他意外错误。我们将展示
.then()/.catch()方法,但主要使用async/await语法。
然后和捕捉
使用现代JS可以用两种方式处理承诺--上面展示的async/await语法,以及.then() 和.catch() 方法。请注意,这两种方法可以产生相同的功能,但async/await通常被认为更容易操作,在较长的承诺链中需要更少的模板代码。
下面是你如何实现同样的事情,但使用then/catch方法。
axios.get('/my-api-route')
.then(res => {
// Work with the response...
}).catch(err => {
// Handle error
console.log(err);
});
res 和err 对象都与ync/await的语法相同。
处理错误
在这一节中,我们将研究两类主要的问题,以及可能遇到的其他问题和如何使用Axios来管理它们。关键是你要明白这适用于Axios处理的所有类型的HTTP查询,包括GET,POST,PATCH ,等等。
这里你可以看到三个方面的语法--这将捕捉到错误;关键是要注意这个错误带有一个大的错误对象,有很多信息。
try {
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
if (err.response) {
// The client was given an error response (5xx, 4xx)
} else if (err.request) {
// The client never received a response, and the request was never left
} else {
// Anything else
}
}
错误对象中的差异,在上面的catch 代码中强调,表明请求在哪里遇到了问题。我们将在下面的章节中更深入地研究这个问题。
error.response
这是我们最熟悉的错误类型,处理起来也更容易。许多网站根据API提供的内容显示404 Not Found页面/错误信息或各种响应代码;这通常是通过响应处理的。
如果你的错误对象有一个响应属性,它标志着你的服务器返回一个4xx/5xx错误。这将帮助你选择什么样的消息返回给用户;你想为4xx提供的消息可能与5xx不同,如果你的后端根本没有返回任何东西。
try {
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
if (err.response) {
// The client was given an error response (5xx, 4xx)
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else if (err.request) {
// The client never received a response, and the request was never left
} else {
// Anything else
}
}
error.request
这种错误最常见的原因是网络不好/不畅,后端挂起,不能即时响应每个请求,未经授权或跨域的请求,最后是后端API返回错误。
**注意:**这发生在浏览器能够发起请求,但由于任何原因没有收到有效的答复。
try {
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
if (err.response) {
// The client was given an error response (5xx, 4xx)
} else if (err.request) {
// The client never received a response, and the request was never left
console.log(err.request);
} else {
// Anything else
}
}
前面我们提到,Axios使用的底层请求取决于它的运行环境。err.request 对象的情况也是如此。这里的err.request 对象在浏览器中执行时是XMLHttpRequest 的实例,而在Node.js中使用时是http.ClientRequest 的实例。
其他错误
错误对象有可能没有附加response 或request 对象。在这种情况下,这意味着在设置请求时有一个问题,最终引发了一个错误。
try {
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
if (err.response) {
// The client was given an error response (5xx, 4xx)
} else if (err.request) {
// The client never received a response, and the request was never left
} else {
// Anything else
console.log('Error', err.message);
}
}
例如,如果你在.get() 的调用中省略了URL参数,从而没有发出请求,就可能是这种情况。
总结
在这篇短文中,我们看了我们如何在Axios中处理各种失败和错误。这对于向你的应用程序/网站访问者提供正确的信息也很重要,而不是总是返回一个通用的错误信息,发送404,或指示网络问题。