Three errors description and basic solutions
1. Network error exception error
When an exception (such as network nowhere) network appears, the send request trigger event error XMLHTTPRequest object instance. Thus, we can catch such errors in onerror event callback function.
We add the following code xhr.ts in:
...
request.onerror = function handleError() {
reject(new Error('Network error'))
}
...
2. Time-out error
We can set the timeout request a timeout, that is, when the request is sent over a certain time still have not received appropriate, the request is automatically terminated and trigger timeout event.
Request the default timeout is 0, that never expires, so we first need to allow the program to configure the timeout:
export interface AxiosRequestConfig {
// ...
timeout?: number
}
Then add the following code xhr function:
const { /**...*/ timeout } = config
if (timeout) {
request.timeout = timeout
}
request.ontimeout = function handleTimeout() {
reject(new Error('Timeout error'))
}
3. The status code error
For state code is not between 200-300, the feedback error
function handleResponse(response: AxiosResponse): void {
// 错误情况3: 状态码错误
if (response.status >= 200 && response.status < 300) {
resolve(response)
} else {
reject(new Error(`Request failed with the code ${response.status}`))
}
}
Enhanced Error Messages
Above, we can handle common exception error situation, and receive an error message returned. However, we may also hope to receive more error messages, such as information request, and so on.
// 举个栗子,我们能在请求回调中,拿到更多错误信息,并进行分析
axios({
method: 'get',
url: '/error/timeout',
timeout: 2000
}).then(res => {
console.log(res)
}).catch((e: AxiosError) => {
console.log(e.message)
console.log(e.request)
console.log(e.code)
})
In this way, we can gather more information about the error, and further make the appropriate treatment for this chestnut above, we begin to continue to escalate
1. Create a class AxiosError
We first define AxiosError type interface for external use
types / index.ts
export interface AxiosError extends Error {
config: AxiosRequestConfig
code?: string
request?: any
response?: AxiosResponse
isAxiosError: boolean
}
Next, we create error.ts file, and then realize AxiosError class, which is integrated in the Error class. Note: Next there will be a pit, For more information, please click to see my other article
/** helpers/error.ts */
import { AxiosRequestConfig, AxiosResponse } from '../types'
export class AxiosError extends Error {
isAxiosError: boolean
config: AxiosRequestConfig
code?: string | null
request?: any
response?: AxiosResponse
constructor(
message: string,
config: AxiosRequestConfig,
code?: string | null,
request?: any,
response?: AxiosResponse
) {
super(message)
this.config = config
this.code = code
this.request = request
this.response = response
this.isAxiosError = true
/** 解决ts集成Error 等的一个坑 */
Object.setPrototypeOf(this, AxiosError.prototype)
}
}
export function createError(
message: string,
config: AxiosRequestConfig,
code?: string | null,
request?: any,
response?: AxiosResponse
) {
const error = new AxiosError(message, config, code, request, response)
return error
}
Finally, we have enhanced the above three error method Solutions
...
// 错误情况1: 网络错误
request.onerror = function handleError() {
reject(createError('Network error', config, null, request))
}
// 错误情况2: 超时错误
request.ontimeout = function handleTimeout() {
reject(createError(`Timeout of ${timeout} error`, config, 'ECONNABORTED', request))
}
// 错误情况3: 状态码错误
function handleResponse(response: AxiosResponse): void {
if (response.status >= 200 && response.status < 300) {
resolve(response)
} else {
reject(
createError(
`Request failed with the code ${response.status}`,
config,
null,
request,
response
)
)
}
...