处理错误
Axios 错误的一般结构如下:
¥The general structure of axios errors is as follows:
-
message - 错误消息和失败状态的简要概述。
¥message - A quick summary of the error message and the status it failed with.
-
name - 这定义了错误的来源。对于 axios,它始终是 'AxiosError'。
¥name - This defines where the error originated from. For axios, it will always be an 'AxiosError'.
-
stack - 提供错误的堆栈跟踪。
¥stack - Provides the stack trace of the error.
-
config - 一个 axios 配置对象,其中包含用户在请求发出时定义的特定实例配置。
¥config - An axios config object with specific instance configurations defined by the user from when the request was made.
-
code - 表示 Axios 识别的错误。下表列出了内部 axios 错误的具体定义。
¥code - Represents an axios identified error. The table below lists out specific definitions for internal axios error.
-
status - HTTP 响应状态码。有关常见的 HTTP 响应状态码含义,请参阅 此处。
¥status - HTTP response status code. See here for common HTTP response status code meanings.
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
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
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
使用 validateStatus
配置选项,你可以定义应该抛出错误的 HTTP 代码。
¥Using the validateStatus
config option, you can define HTTP code(s) that should throw an error.
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Resolve only if the status code is less than 500
}
})
使用 toJSON
可以得到一个对象,其中包含有关 HTTP 错误的更多信息。
¥Using toJSON
you get an object with more information about the HTTP error.
axios.get('/user/12345')
.catch(function (error) {
console.log(error.toJSON());
});