Skip to content

Commit

Permalink
refactor(projects): axios封装:文件夹规范,错误处理完善
Browse files Browse the repository at this point in the history
  • Loading branch information
Soybean committed Nov 22, 2021
1 parent c81221e commit 451c754
Show file tree
Hide file tree
Showing 10 changed files with 88 additions and 46 deletions.
2 changes: 1 addition & 1 deletion .env.development
@@ -1,4 +1,4 @@
#请求的环境
VITE_HTTP_ENV=DEV
#请求地址
VITE_HTTP_URL=http://192.168.100.57/
VITE_HTTP_URL=http://192.168.100.43:8201
2 changes: 1 addition & 1 deletion .env.production
@@ -1,4 +1,4 @@
#请求的环境 正式环境
VITE_HTTP_ENV=PROD
#请求地址
VITE_HTTP_URL=http://119.23.220.176:17321
VITE_HTTP_URL=http://192.168.100.43:8201
2 changes: 1 addition & 1 deletion .env.staging
@@ -1,3 +1,3 @@
VITE_HTTP_ENV=STAGING
#请求地址
VITE_HTTP_URL=http://119.23.220.176:17321
VITE_HTTP_URL=http://192.168.100.43:8201
Empty file.
9 changes: 8 additions & 1 deletion src/service/api/auth.ts
@@ -1 +1,8 @@
export {};
import { request } from '../request';

/**
* 获取数据字典
*/
export async function fetchDictionary(keyword: string) {
await request.post('/ehe/model/getByIndicator', { indiCatorName: keyword });
}
18 changes: 9 additions & 9 deletions src/service/request/axios/instance.ts
@@ -1,9 +1,9 @@
import axios from 'axios';
import type { AxiosRequestConfig, AxiosInstance, CancelTokenStatic } from 'axios';
import type { AxiosRequestConfig, AxiosInstance, AxiosError, CancelTokenStatic } from 'axios';
import { getToken } from '@/utils';
import { transformRequestData, handleResponseError } from '../helpers';
import { transformRequestData, handleAxiosError, handleResponseError } from '../helpers';

export interface StatusConfig {
interface StatusConfig {
/** 表明请求状态的属性key */
statusKey: string;
/** 请求信息的属性key */
Expand Down Expand Up @@ -34,7 +34,7 @@ export default class CustomAxiosInstance {
}

/** 设置请求拦截器 */
setInterceptor(): void {
setInterceptor() {
this.instance.interceptors.request.use(
async config => {
const handleConfig = { ...config };
Expand All @@ -46,8 +46,8 @@ export default class CustomAxiosInstance {
}
return handleConfig;
},
error => {
handleResponseError(error);
(error: AxiosError) => {
handleAxiosError(error);
return Promise.reject(error);
}
);
Expand All @@ -64,11 +64,11 @@ export default class CustomAxiosInstance {
return Promise.reject(responseData[msgKey]);
}
const error = { response };
handleResponseError(error);
handleResponseError(response);
return Promise.reject(error);
},
error => {
handleResponseError(error);
(error: AxiosError) => {
handleAxiosError(error);
return Promise.reject(error);
}
);
Expand Down
27 changes: 27 additions & 0 deletions src/service/request/config/index.ts
@@ -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版本不支持该请求~'
};
60 changes: 29 additions & 31 deletions src/service/request/helpers/error.ts
@@ -1,50 +1,48 @@
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版本不支持该请求~'
};
import type { AxiosError, AxiosResponse } from 'axios';
import { DEFAULT_REQUEST_ERROR_MSG, ERROR_STATUS, NETWORK_ERROR_MSG } from '../config';

type ErrorStatus = keyof typeof ERROR_STATUS;

type ErrorMsg = [boolean, string];
/**
* 获取请求失败的错误
* @param error
*/
export function getFailRequestErrorMsg(error: any) {
const errorAction: ErrorMsg[] = [
[!window.navigator.onLine || error.message === 'Network Error', '网络不可用~'],
[error.code === 'ECONNABORTED' && error.message.includes('timeout'), '网络连接超时~'],
[error.response, ERROR_STATUS[error.response.status as ErrorStatus]]
];
let errorMsg = '请求错误~';
errorAction.some(item => {
const [flag, msg] = item;
if (flag) {
errorMsg = msg;
}
return flag;
});
return errorMsg;
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 handleResponseError(error: any) {
export function handleAxiosError(error: AxiosError) {
const { $message: Message } = window;

const msg = getFailRequestErrorMsg(error);

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;
}
7 changes: 7 additions & 0 deletions src/service/request/helpers/transform.ts
Expand Up @@ -3,6 +3,11 @@ import FormData from 'form-data';
import { isArray } from '@/utils';
import { ContentType } from '@/enum';

/**
* 请求数据的转换
* @param requestData - 请求数据
* @param contentType - 请求头的Content-Type
*/
export async function transformRequestData(requestData: any, contentType?: string) {
// application/json类型不处理
let data = requestData;
Expand All @@ -27,13 +32,15 @@ export async function transformRequestData(requestData: any, contentType?: strin
async function transformFile(file: File[] | File, key: string) {
const formData = new FormData();
if (isArray(file)) {
// 多文件
await Promise.all(
(file as File[]).map(item => {
formData.append(key, item);
return true;
})
);
} else {
// 单文件
await formData.append(key, file);
}
return formData;
Expand Down
7 changes: 5 additions & 2 deletions src/service/request/index.ts
@@ -1,5 +1,8 @@
import { createRequest } from './axios';
import { REQUEST_TIMEOUT, REQUEST_TIMEOUT_MSG } from './config';

export const adminRequest = createRequest({
baseURL: import.meta.env.VITE_HTTP_URL_EMOSS_ADMIN as string
export const request = createRequest({
baseURL: import.meta.env.VITE_HTTP_URL,
timeout: REQUEST_TIMEOUT,
timeoutErrorMessage: REQUEST_TIMEOUT_MSG
});

1 comment on commit 451c754

@vercel
Copy link

@vercel vercel bot commented on 451c754 Nov 22, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.