refactor(http): 升级alova到v3, 优化状态码和逻辑错误处理

This commit is contained in:
h_mo 2024-08-20 14:30:40 +08:00
parent 26a8bfba42
commit 5a705f9a44
9 changed files with 48 additions and 17 deletions

View File

@ -35,7 +35,7 @@ export function createVitePlugins({ isProd }: VitePluginConfig): PluginOption[]
'uni-mini-router': ['useRouter', 'useRoute'], 'uni-mini-router': ['useRouter', 'useRoute'],
}, },
{ {
alova: ['useRequest'], 'alova/client': ['useRequest'],
}, },
], ],
dts: 'typings/auto-imports.d.ts', dts: 'typings/auto-imports.d.ts',

View File

@ -36,8 +36,8 @@
"postinstall": "weapp-tw patch" "postinstall": "weapp-tw patch"
}, },
"dependencies": { "dependencies": {
"@alova/adapter-uniapp": "^1.2.2", "@alova/adapter-uniapp": "^2.0.4",
"@alova/mock": "^1.5.2", "@alova/mock": "^2.0.4",
"@dcloudio/uni-app": "3.0.0-alpha-4020520240808001", "@dcloudio/uni-app": "3.0.0-alpha-4020520240808001",
"@dcloudio/uni-app-plus": "3.0.0-alpha-4020520240808001", "@dcloudio/uni-app-plus": "3.0.0-alpha-4020520240808001",
"@dcloudio/uni-components": "3.0.0-alpha-4020520240808001", "@dcloudio/uni-components": "3.0.0-alpha-4020520240808001",
@ -52,7 +52,7 @@
"@dcloudio/uni-mp-weixin": "3.0.0-alpha-4020520240808001", "@dcloudio/uni-mp-weixin": "3.0.0-alpha-4020520240808001",
"@dcloudio/uni-quickapp-webview": "3.0.0-alpha-4020520240808001", "@dcloudio/uni-quickapp-webview": "3.0.0-alpha-4020520240808001",
"@multiavatar/multiavatar": "^1.0.7", "@multiavatar/multiavatar": "^1.0.7",
"alova": "^2.21.4", "alova": "^3.0.9",
"crypto-js": "^4.2.0", "crypto-js": "^4.2.0",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"pinia": "^2.2.2", "pinia": "^2.2.2",

View File

@ -19,7 +19,7 @@ function handleLoginOut() {
<template> <template>
<view class="text-md pt-36"> <view class="text-md pt-36">
<view v-if="loggedIn" class="text-center"> <view v-if="loggedIn" class="text-center">
<image class="h-56 w-56" :src="userInfo?.avatar" /> <image class="h-8 w-8" :src="userInfo?.avatar" />
<view class="mt-2"> <view class="mt-2">
{{ userInfo?.nickname }} {{ userInfo?.nickname }}
</view> </view>

View File

@ -8,7 +8,7 @@ const appTitle = 'uniapp-vue3';
<template> <template>
<view class="flex flex-col items-center gap-y-2 pt-36"> <view class="flex flex-col items-center gap-y-2 pt-36">
<image :src="logo" class="h-56 w-56" alt="" mode="widthFix" /> <image :src="logo" class="h-8 w-8" alt="" mode="widthFix" />
<view class="text-xl font-semibold"> <view class="text-xl font-semibold">
{{ appTitle }} {{ appTitle }}
</view> </view>

View File

@ -12,7 +12,7 @@ const userStore = useUserStore();
<view class="mt-36 text-center"> <view class="mt-36 text-center">
登录后访问log 登录后访问log
</view> </view>
<image class="my-4 h-48 w-48" :src="userStore.userInfo?.avatar" mode="aspectFit" lazy-load="false" binderror="" bindload="" /> <image class="my-4 h-8 w-8" :src="userStore.userInfo?.avatar" mode="aspectFit" lazy-load="false" binderror="" bindload="" />
<view>{{ userStore.userInfo?.nickname }}</view> <view>{{ userStore.userInfo?.nickname }}</view>
</view> </view>
</template> </template>

View File

@ -8,7 +8,6 @@ export function createRouterGuard(router: Router) {
function createBeforeEachGuard(router: Router) { function createBeforeEachGuard(router: Router) {
router.beforeEach((to, _, next) => { router.beforeEach((to, _, next) => {
console.log('beforeEach', to);
const _isLogin = isLogin(); const _isLogin = isLogin();
if (to && to?.meta?.ignoreAuth) { if (to && to?.meta?.ignoreAuth) {
// 如果目标路由忽略验证直接跳转 // 如果目标路由忽略验证直接跳转
@ -39,6 +38,5 @@ function createAfterEachGuard(router: Router) {
// 如果已经登录且目标页面是登录页面则跳转至首页 // 如果已经登录且目标页面是登录页面则跳转至首页
router.replaceAll({ name: 'Home' }); router.replaceAll({ name: 'Home' });
} }
console.log('afterEach', to);
}); });
} }

View File

@ -1,5 +1,4 @@
import { defineStore } from 'pinia'; import { defineStore } from 'pinia';
import { useRequest } from 'alova';
import { getUserInfoApi } from '@/services/api/user'; import { getUserInfoApi } from '@/services/api/user';
import type { UserInfoModel } from '@/services/model/userModel'; import type { UserInfoModel } from '@/services/model/userModel';
import { login as loginApi } from '@/services/api/auth'; import { login as loginApi } from '@/services/api/auth';

View File

@ -1,6 +1,12 @@
import { Toast } from '@/utils/uniapi/prompt'; import { Toast } from '@/utils/uniapi/prompt';
import type { ResultEnum } from '@/enums/httpEnum';
export function checkStatus(status: number, msg: string): void { /**
* Http错误处理
* @param status
* @param msg
*/
export function handleHttpStatus(status: number, msg: string): void {
let errMessage = null; let errMessage = null;
switch (status) { switch (status) {
case 400: case 400:
@ -49,3 +55,22 @@ export function checkStatus(status: number, msg: string): void {
Toast(errMessage); Toast(errMessage);
} }
} }
/**
*
*/
export function handleLogicError(errCode: ResultEnum, errMsg?: string) {
switch (errCode) {
case ResultEnum.ERROR:
// TODO ERROR处理
// ...
break;
case ResultEnum.FAIL:
// TODO FAIL处理
// ...
break;
}
if (errMsg) {
Toast(errMsg);
}
}

View File

@ -1,7 +1,7 @@
import { createAlova } from 'alova'; import { createAlova } from 'alova';
import AdapterUniapp from '@alova/adapter-uniapp'; import AdapterUniapp from '@alova/adapter-uniapp';
import { assign } from 'lodash-es'; import { assign } from 'lodash-es';
import { checkStatus } from './checkStatus'; import { handleHttpStatus, handleLogicError } from './faultTolerance';
import { getBaseUrl, isUseMock } from '@/utils/env'; import { getBaseUrl, isUseMock } from '@/utils/env';
import { mockAdapter } from '@/mock'; import { mockAdapter } from '@/mock';
import { ContentTypeEnum, ResultEnum } from '@/enums/httpEnum'; import { ContentTypeEnum, ResultEnum } from '@/enums/httpEnum';
@ -28,7 +28,7 @@ const alovaInstance = createAlova({
/* #endif */ /* #endif */
}), }),
timeout: 5000, timeout: 5000,
beforeRequest: (method) => { beforeRequest: async (method) => {
method.config.headers = assign(method.config.headers, ContentType); method.config.headers = assign(method.config.headers, ContentType);
const { config } = method; const { config } = method;
const ignoreAuth = !config.meta?.ignoreAuth; const ignoreAuth = !config.meta?.ignoreAuth;
@ -57,17 +57,26 @@ const alovaInstance = createAlova({
if (code === ResultEnum.SUCCESS) { if (code === ResultEnum.SUCCESS) {
return data as any; return data as any;
} }
checkStatus(statusCode, message || ''); // 逻辑错误处理,与业务相关
handleLogicError(code, message);
throw new Error(`请求错误[${code}]${message}`); throw new Error(`请求错误[${code}]${message}`);
} }
throw new Error(`请求错误[${statusCode}]${errMsg}`); // 处理http状态错误
handleHttpStatus(statusCode, message || '');
throw new Error(`HTTP请求错误[${statusCode}]${errMsg}`);
}, },
/** /**
* *
*/ */
onError: (err) => { onError: async (err) => {
throw new Error(`请求错误:${err}`); throw new Error(`请求失败:${err}`);
},
/**
* ,
*/
onComplete: async () => {
// 处理请求完成逻辑
}, },
}, },
}); });