refactor(projects): axios封装完成

This commit is contained in:
Soybean
2021-11-23 00:23:43 +08:00
parent 451c7547af
commit 03b398af2f
21 changed files with 332 additions and 145 deletions

View File

@@ -1,37 +1,45 @@
import type { AxiosError, AxiosResponse } from 'axios';
import { DEFAULT_REQUEST_ERROR_MSG, ERROR_STATUS, NETWORK_ERROR_MSG } from '../config';
import type { RequestServiceError, BackendServiceResult } from '@/interface';
import {
DEFAULT_REQUEST_ERROR_CODE,
DEFAULT_REQUEST_ERROR_MSG,
NETWORK_ERROR_CODE,
NETWORK_ERROR_MSG,
REQUEST_TIMEOUT_CODE,
REQUEST_TIMEOUT_MSG,
ERROR_STATUS
} from '../config';
import { showErrorMsg } from './msg';
type ErrorStatus = keyof typeof ERROR_STATUS;
/**
* 获取请求失败的错误
* @param error
*/
export function getFailRequestErrorMsg(error: AxiosError) {
if (!window.navigator.onLine || error.message === 'Network Error') {
return NETWORK_ERROR_MSG;
}
if (error.code === 'ECONNABORTED') {
return error.message;
}
if (error.response) {
const errorCode: ErrorStatus = error.response.status as ErrorStatus;
const msg = ERROR_STATUS[errorCode] || DEFAULT_REQUEST_ERROR_MSG;
return msg;
}
return DEFAULT_REQUEST_ERROR_MSG;
}
/**
* 处理请求失败的错误
* @param error - 错误
*/
export function handleAxiosError(error: AxiosError) {
const { $message: Message } = window;
export function handleAxiosError(axiosError: AxiosError) {
const error: RequestServiceError = {
type: 'axios',
code: DEFAULT_REQUEST_ERROR_CODE,
msg: DEFAULT_REQUEST_ERROR_MSG
};
const msg = getFailRequestErrorMsg(error);
if (!window.navigator.onLine || axiosError.message === 'Network Error') {
// 网路错误
Object.assign(error, { code: NETWORK_ERROR_CODE, msg: NETWORK_ERROR_MSG });
} else if (axiosError.code === REQUEST_TIMEOUT_CODE && axiosError.message.includes('timeout')) {
/** 超时错误 */
Object.assign(error, { code: REQUEST_TIMEOUT_CODE, msg: REQUEST_TIMEOUT_MSG });
} else if (axiosError.response) {
// 请求不成功的错误
const errorCode: ErrorStatus = axiosError.response.status as ErrorStatus;
const msg = ERROR_STATUS[errorCode] || DEFAULT_REQUEST_ERROR_MSG;
Object.assign(error, { code: errorCode, msg });
}
Message?.error(msg);
showErrorMsg(error);
return error;
}
/**
@@ -39,10 +47,39 @@ export function handleAxiosError(error: AxiosError) {
* @param response - 请求的响应
*/
export function handleResponseError(response: AxiosResponse) {
const error: RequestServiceError = {
type: 'axios',
code: DEFAULT_REQUEST_ERROR_CODE,
msg: DEFAULT_REQUEST_ERROR_MSG
};
if (!window.navigator.onLine) {
return NETWORK_ERROR_MSG;
// 网路错误
Object.assign(error, { code: NETWORK_ERROR_CODE, msg: NETWORK_ERROR_MSG });
} else {
// 请求成功的状态码非200的错误
const errorCode: ErrorStatus = response.status as ErrorStatus;
const msg = ERROR_STATUS[errorCode] || DEFAULT_REQUEST_ERROR_MSG;
Object.assign(error, { type: 'backend', code: errorCode, msg });
}
const errorCode: ErrorStatus = response.status as ErrorStatus;
const msg = ERROR_STATUS[errorCode] || DEFAULT_REQUEST_ERROR_MSG;
return msg;
showErrorMsg(error);
return error;
}
/**
* 处理后端返回的错误
* @param backendResult - 后端接口的响应数据
*/
export function handleBackendError(backendResult: BackendServiceResult) {
const error: RequestServiceError = {
type: 'backend',
code: backendResult.code,
msg: backendResult.message
};
showErrorMsg(error);
return error;
}

View File

@@ -1,16 +1,26 @@
// type ResultHandler<T> = (...arg: any) => T;
// type SuccessRequest<T> = {
// error: null;
// data: T;
// };
// type FailRequest = {
// error: any;
// data: null;
// };
// type RequestResult<T> = SuccessRequest<T> | FailRequest;
// /**
// * 对请求的结果数据进行格式化的处理
// * @param handleFunc - 处理函数
// * @param requests - 请求结果
// */
// export function handleResponse<ResponseData>(resultHandler: ResultHandler<ResponseData>, requests: RequestResult[]) {}
import { CustomRequestResult, CustomSuccessRequestResult, CustomFailRequestResult } from '@/interface';
type ResultHandler<T> = (...arg: any) => T;
/**
* 对请求的结果数据进行格式化的处理
* @param resultHandler - 处理函数
* @param requests - 请求结果
*/
export function resultMiddleware<MiddlewareData>(
resultHandler: ResultHandler<MiddlewareData>,
requests: CustomRequestResult<any>[]
) {
const errorIndex = requests.findIndex(item => item.error !== null);
const hasError = errorIndex > -1;
const successResult: CustomSuccessRequestResult<MiddlewareData> = {
data: resultHandler(...requests.map(item => item.data)),
error: null,
networkStatus: window.navigator.onLine
};
const failResult: CustomFailRequestResult = {
data: null,
error: requests[errorIndex].error!,
networkStatus: window.navigator.onLine
};
return hasError ? failResult : successResult;
}

View File

@@ -1,2 +1,3 @@
export * from './transform';
export * from './error';
export * from './handler';

View File

@@ -0,0 +1,31 @@
import type { RequestServiceError } from '@/interface';
import { NO_ERROR_MSG_CODE, ERROR_MSG_DURATION } from '../config';
/** 错误消息栈,防止同一错误同时出现 */
const errorMsgStack = new Map<string | number, string>([]);
function addErrorMsg(error: RequestServiceError) {
errorMsgStack.set(error.code, error.msg);
}
function removeErrorMsg(error: RequestServiceError) {
errorMsgStack.delete(error.code);
}
function hasErrorMsg(error: RequestServiceError) {
return errorMsgStack.has(error.code);
}
/**
* 显示错误信息
* @param error
*/
export function showErrorMsg(error: RequestServiceError) {
if (!NO_ERROR_MSG_CODE.includes(error.code)) {
if (!hasErrorMsg(error)) {
addErrorMsg(error);
window.$message?.error(error.msg, { duration: ERROR_MSG_DURATION });
setTimeout(() => {
removeErrorMsg(error);
}, ERROR_MSG_DURATION);
}
}
}