封装---统一处理接口与打印错误信息
一.简介
我在重构代码时突然想到一个想法并实现出来:封装一个统一处理接口与打印错误信息,控制显示错误信息在控制台,接口请求时loading效果展示等等
这个只是个人想法,而且比较简略,不太清楚实际工作是否这样写,但是我认为只要有这个想法就要去实现,总比没实现好,欢迎大家的建议与指导
介绍我在项目中如何封装一个统一的 API 请求函数,解决每个接口都要写
try...catch
的繁琐问题,并实现自动错误日志、toast 提示等功能,助力开发效率提升。
在日常开发中,我们常常会写很多类似这样的代码:
try {const res = await axios.get('/api/user')console.log('请求成功', res)
} catch (error) {console.error('请求失败', error)
}
当 API 请求数量增多,每个都写一遍 try...catch
,不仅重复代码多,而且难以统一管理。
于是我封装了一个 apiRequest
方法,来统一处理:
在上一篇文章中,我详细写了关于封装try...catch的封装文章:
封装---优化try..catch错误处理方式
已经能够实现下面的效果:
const [Response, Error] = await apiRequest(fetch('/api'))
if (Error) {
// 需要打印errorconsole.log(Error)
}
// 处理返回值代码部分
console.log(Response)
接下来进行拓展到能够实现下面的效果:
这样统一内部处理错误信息提示,控制台打印规范统一的错误信息,显示正确信息提示等等,核心业务代码逻辑就可以更好的在下面进行书写
二.实现
1.单个接口(使用apiRequest函数)
首先就是工具函数的封装,我才用ts来写:
import { toast } from '@/lib/utils/toast'interface ApiRequestOptions {requestName?: stringshowRequestName?: booleanshowSuccessLog?: booleanshowErrorLog?: booleanshowSuccessToast?: booleansuccessToastMessage?: stringshowErrorToast?: booleanerrorToastMessage?: string
}const apiRequest = async <T = any>(promise: Promise<T>, options: ApiRequestOptions = {}): Promise<[T | null, any | null]> => {const {requestName = '请求',showRequestName = true,showSuccessLog = false,showErrorLog = true,showSuccessToast = false,successToastMessage = '请求成功',showErrorToast = false,errorToastMessage = '请求失败'} = optionstry {const response = await promiseif (showRequestName && showSuccessLog) {console.log(`[${requestName}] 请求成功:`, response)}if (showSuccessToast) {toast.success(successToastMessage)}return [response, null]} catch (error) {if (showRequestName && showErrorLog) {console.error(`[${requestName}] 请求失败:`, error)}if (showErrorToast) {toast.error(errorToastMessage)}return [null, error]}
}
上面中的函数apiRequest接收两个参数:
- promise接口
- 配置参数数据
这样的情况下根据配置参数就可以决定是否需要打印信息,控制信息提示等等(可以自行进行拓展)
使用示例:
// apis/user.ts
import http from '@/lib/utils/request/http'export const getUserInfo = (id: number) => {return http.get(`/api/user/${id}`)
}
使用 apiRequest
调用该函数:
// pages/user.ts
import { apiRequest } from '@/lib/utils/apiRequest'
import { getUserInfo } from '@/apis/user'async function fetchUser() {const [res, error] = await apiRequest(getUserInfo(1), {requestName: '获取用户信息',showSuccessLog: true,showSuccessToast: true,successToastMessage: '获取用户成功',showErrorLog: true,showErrorToast: true,errorToastMessage: '获取用户失败'})if (!error) {console.log('用户数据:', res.data)}
}
2.多个接口统一封装配置
工具函数:
import { toast } from '@/lib/utils/toast'// 后续可以添加更多内容拓展
interface ApiRequestOptions {requestName?: stringshowRequestName?: booleanshowSuccessLog?: booleanshowErrorLog?: booleanshowSuccessToast?: booleansuccessToastMessage?: stringshowErrorToast?: booleanerrorToastMessage?: string
}// 适合于封装多个请求的函数,注意那个api请求药味对象封装形式
interface WrapRequestOptions {defaultOptions?: ApiRequestOptionsrequestNameMap?: Record<string, string>
}const apiRequest = async <T = any>(promise: Promise<T>, options: ApiRequestOptions = {}): Promise<[T | null, any | null]> => {const {requestName = '请求',showRequestName = true,showSuccessLog = false,showErrorLog = true,showSuccessToast = false,successToastMessage = '请求成功',showErrorToast = false,errorToastMessage = '请求失败'} = optionstry {const response = await promiseif (showRequestName && showSuccessLog) {console.log(`[${requestName}] 请求成功:`, response)}if (showSuccessToast) {toast.success(successToastMessage) }return [response, null]} catch (error) {if (showRequestName && showErrorLog) {console.error(`[${requestName}] 请求失败:`, error)}if (showErrorToast) {toast.error(errorToastMessage)}return [null, error]}
}function wrapRequestObject<T extends Record<string, any>>(apiObject: T, config: WrapRequestOptions = {}): { [K in keyof T]: (...args: Parameters<T[K]>) => ReturnType<typeof apiRequest> } {const wrapped = {} as anyfor (const key in apiObject) {const func = apiObject[key]wrapped[key] = (...args: any[]) => {// 取出用户传入的 options(最后一个参数,且为对象)let options = {}if (args.length > 1 && typeof args[args.length - 1] === 'object' && !Array.isArray(args[args.length - 1]) && !(args[args.length - 1] instanceof File)) {options = args.pop()}const promise = func(...args)const requestName = config?.requestNameMap?.[key] || keyreturn apiRequest(promise, {...config?.defaultOptions,...options,requestName: requestName})}}return wrapped
}export { apiRequest, wrapRequestObject }
(1).原始接口定义(以教师管理为例)
// apis/teacher-management.api.ts
import http from '@/lib/utils/request/http'export default {get_teacher_list: (params: { page: number; pageSize: number }) =>http.get('/v1/teachers', { params }),add_teacher: (data: any) => http.post('/v1/teachers', data),update_teacher: (data: any) => http.put('/v1/teachers', data),delete_teacher: (id: number) => http.delete(`/v1/teachers/${id}`)
}
(2).封装 wrapRequestObject
配置
可以统一配置封装这一个对象中的接口函数以及配置)
需要对其中的接口配置只需要单独
// apis/index.ts
import { wrapRequestObject } from '@/lib/utils/apiRequest'
import TeacherAPI_Raw from './teacher-management.api'const TeacherManagement_API = wrapRequestObject(TeacherAPI_Raw, {defaultOptions: {showRequestName: true,showSuccessToast: true,showErrorToast: true,showErrorLog: true,successToastMessage: '请求成功',errorToastMessage: '请求失败'},requestNameMap: {get_teacher_list: '获取教师列表',add_teacher: '新增教师',update_teacher: '修改教师',delete_teacher: '删除教师'}
})export { TeacherManagement_API }
(3).页面中调用示例(带局部覆盖配置)
const [res, err] = await TeacherManagement_API.add_teacher({ name: '张三' }, {successToastMessage: '添加教师成功!',showSuccessLog: true
})if (!err) {console.log('添加成功:', res)
}
三.优势
优势 | 说明 |
---|---|
简洁性 | 一行代码搞定 try/catch、toast、log |
灵活性 | 每个请求支持单独传参 |
可维护性 | 统一处理日志与提示,便于维护与调试 |
可读性 | requestNameMap 提高开发者阅读效率 |
这个封装方式非常适用于大型项目,尤其是 SvelteKit、Vue、React 项目中的 API 请求管理。你可以根据项目具体需求,扩展更多功能,比如 loading 管理、请求时间统计、埋点分析等。
就比如像下面的代码一样:(效果展示)
可以统一项目中的信息控制台错误打印等,实际使用接口只需要一行,其他内容写业务逻辑