refactor(projects): axios封装:文件夹规范,错误处理完善

This commit is contained in:
Soybean 2021-11-22 18:31:57 +08:00
parent c81221efac
commit 451c7547af
10 changed files with 88 additions and 46 deletions

View File

@ -1,4 +1,4 @@
#请求的环境 #请求的环境
VITE_HTTP_ENV=DEV VITE_HTTP_ENV=DEV
#请求地址 #请求地址
VITE_HTTP_URL=http://192.168.100.57/ VITE_HTTP_URL=http://192.168.100.43:8201

View File

@ -1,4 +1,4 @@
#请求的环境 正式环境 #请求的环境 正式环境
VITE_HTTP_ENV=PROD VITE_HTTP_ENV=PROD
#请求地址 #请求地址
VITE_HTTP_URL=http://119.23.220.176:17321 VITE_HTTP_URL=http://192.168.100.43:8201

View File

@ -1,3 +1,3 @@
VITE_HTTP_ENV=STAGING VITE_HTTP_ENV=STAGING
#请求地址 #请求地址
VITE_HTTP_URL=http://119.23.220.176:17321 VITE_HTTP_URL=http://192.168.100.43:8201

View File

View File

@ -1 +1,8 @@
export {}; import { request } from '../request';
/**
*
*/
export async function fetchDictionary(keyword: string) {
await request.post('/ehe/model/getByIndicator', { indiCatorName: keyword });
}

View File

@ -1,9 +1,9 @@
import axios from 'axios'; import axios from 'axios';
import type { AxiosRequestConfig, AxiosInstance, CancelTokenStatic } from 'axios'; import type { AxiosRequestConfig, AxiosInstance, AxiosError, CancelTokenStatic } from 'axios';
import { getToken } from '@/utils'; import { getToken } from '@/utils';
import { transformRequestData, handleResponseError } from '../helpers'; import { transformRequestData, handleAxiosError, handleResponseError } from '../helpers';
export interface StatusConfig { interface StatusConfig {
/** 表明请求状态的属性key */ /** 表明请求状态的属性key */
statusKey: string; statusKey: string;
/** 请求信息的属性key */ /** 请求信息的属性key */
@ -34,7 +34,7 @@ export default class CustomAxiosInstance {
} }
/** 设置请求拦截器 */ /** 设置请求拦截器 */
setInterceptor(): void { setInterceptor() {
this.instance.interceptors.request.use( this.instance.interceptors.request.use(
async config => { async config => {
const handleConfig = { ...config }; const handleConfig = { ...config };
@ -46,8 +46,8 @@ export default class CustomAxiosInstance {
} }
return handleConfig; return handleConfig;
}, },
error => { (error: AxiosError) => {
handleResponseError(error); handleAxiosError(error);
return Promise.reject(error); return Promise.reject(error);
} }
); );
@ -64,11 +64,11 @@ export default class CustomAxiosInstance {
return Promise.reject(responseData[msgKey]); return Promise.reject(responseData[msgKey]);
} }
const error = { response }; const error = { response };
handleResponseError(error); handleResponseError(response);
return Promise.reject(error); return Promise.reject(error);
}, },
error => { (error: AxiosError) => {
handleResponseError(error); handleAxiosError(error);
return Promise.reject(error); return Promise.reject(error);
} }
); );

View File

@ -0,0 +1,27 @@
/** 请求超时时间 */
export const REQUEST_TIMEOUT = 60 * 1000;
/** 默认的请求错误文本 */
export const DEFAULT_REQUEST_ERROR_MSG = '请求错误~';
/** 请求超时的错误文本 */
export const REQUEST_TIMEOUT_MSG = '请求超时~';
/** 网络不可用的错误文本 */
export const NETWORK_ERROR_MSG = '网络不可用~';
/** 请求不成功各种状态的错误 */
export const ERROR_STATUS = {
400: '400: 请求出现语法错误',
401: '401: 用户未授权~',
403: '403: 服务器拒绝访问~',
404: '404: 请求的资源不存在~',
405: '405: 请求方法未允许~',
408: '408: 网络请求超时~',
500: '500: 服务器内部错误~',
501: '501: 服务器未实现请求功能~',
502: '502: 错误网关~',
503: '503: 服务不可用~',
504: '504: 网关超时~',
505: '505: http版本不支持该请求~'
};

View File

@ -1,50 +1,48 @@
const ERROR_STATUS = { import type { AxiosError, AxiosResponse } from 'axios';
400: '400: 请求出现语法错误', import { DEFAULT_REQUEST_ERROR_MSG, ERROR_STATUS, NETWORK_ERROR_MSG } from '../config';
401: '401: 用户未授权~',
403: '403: 服务器拒绝访问~',
404: '404: 请求的资源不存在~',
405: '405: 请求方法未允许~',
408: '408: 网络请求超时~',
500: '500: 服务器内部错误~',
501: '501: 服务器未实现请求功能~',
502: '502: 错误网关~',
503: '503: 服务不可用~',
504: '504: 网关超时~',
505: '505: http版本不支持该请求~'
};
type ErrorStatus = keyof typeof ERROR_STATUS; type ErrorStatus = keyof typeof ERROR_STATUS;
type ErrorMsg = [boolean, string];
/** /**
* *
* @param error * @param error
*/ */
export function getFailRequestErrorMsg(error: any) { export function getFailRequestErrorMsg(error: AxiosError) {
const errorAction: ErrorMsg[] = [ if (!window.navigator.onLine || error.message === 'Network Error') {
[!window.navigator.onLine || error.message === 'Network Error', '网络不可用~'], return NETWORK_ERROR_MSG;
[error.code === 'ECONNABORTED' && error.message.includes('timeout'), '网络连接超时~'], }
[error.response, ERROR_STATUS[error.response.status as ErrorStatus]] if (error.code === 'ECONNABORTED') {
]; return error.message;
let errorMsg = '请求错误~'; }
errorAction.some(item => { if (error.response) {
const [flag, msg] = item; const errorCode: ErrorStatus = error.response.status as ErrorStatus;
if (flag) { const msg = ERROR_STATUS[errorCode] || DEFAULT_REQUEST_ERROR_MSG;
errorMsg = msg; return msg;
} }
return flag; return DEFAULT_REQUEST_ERROR_MSG;
});
return errorMsg;
} }
/** /**
* *
* @param error - * @param error -
*/ */
export function handleResponseError(error: any) { export function handleAxiosError(error: AxiosError) {
const { $message: Message } = window; const { $message: Message } = window;
const msg = getFailRequestErrorMsg(error); const msg = getFailRequestErrorMsg(error);
Message?.error(msg); Message?.error(msg);
} }
/**
*
* @param response -
*/
export function handleResponseError(response: AxiosResponse) {
if (!window.navigator.onLine) {
return NETWORK_ERROR_MSG;
}
const errorCode: ErrorStatus = response.status as ErrorStatus;
const msg = ERROR_STATUS[errorCode] || DEFAULT_REQUEST_ERROR_MSG;
return msg;
}

View File

@ -3,6 +3,11 @@ import FormData from 'form-data';
import { isArray } from '@/utils'; import { isArray } from '@/utils';
import { ContentType } from '@/enum'; import { ContentType } from '@/enum';
/**
*
* @param requestData -
* @param contentType - Content-Type
*/
export async function transformRequestData(requestData: any, contentType?: string) { export async function transformRequestData(requestData: any, contentType?: string) {
// application/json类型不处理 // application/json类型不处理
let data = requestData; let data = requestData;
@ -27,6 +32,7 @@ export async function transformRequestData(requestData: any, contentType?: strin
async function transformFile(file: File[] | File, key: string) { async function transformFile(file: File[] | File, key: string) {
const formData = new FormData(); const formData = new FormData();
if (isArray(file)) { if (isArray(file)) {
// 多文件
await Promise.all( await Promise.all(
(file as File[]).map(item => { (file as File[]).map(item => {
formData.append(key, item); formData.append(key, item);
@ -34,6 +40,7 @@ async function transformFile(file: File[] | File, key: string) {
}) })
); );
} else { } else {
// 单文件
await formData.append(key, file); await formData.append(key, file);
} }
return formData; return formData;

View File

@ -1,5 +1,8 @@
import { createRequest } from './axios'; import { createRequest } from './axios';
import { REQUEST_TIMEOUT, REQUEST_TIMEOUT_MSG } from './config';
export const adminRequest = createRequest({ export const request = createRequest({
baseURL: import.meta.env.VITE_HTTP_URL_EMOSS_ADMIN as string baseURL: import.meta.env.VITE_HTTP_URL,
timeout: REQUEST_TIMEOUT,
timeoutErrorMessage: REQUEST_TIMEOUT_MSG
}); });