| | |
| | | * @FilePath: /wot-starter/src/api/core/handlers.ts |
| | | */ |
| | | import type { Method } from 'alova' |
| | | import router from '@/router' |
| | | import { triggerUnauthorizedRedirect } from '@/router/authRedirect' |
| | | import { clearMiniAuthSession } from '@/store/auth' |
| | | |
| | | // Custom error class for API errors |
| | | export class ApiError extends Error { |
| | |
| | | // Define a type for the expected API response structure |
| | | interface ApiResponse { |
| | | code: number |
| | | msg?: string |
| | | data?: any |
| | | message?: string |
| | | result?: any |
| | | success?: boolean |
| | | total?: number |
| | | more?: boolean |
| | | } |
| | | |
| | | let redirectingToLogin = false |
| | | |
| | | function handleUnauthorized(message?: string, code = 401, data?: any) { |
| | | clearMiniAuthSession() |
| | | if (!redirectingToLogin) { |
| | | redirectingToLogin = true |
| | | const globalToast = useGlobalToast() |
| | | globalToast.error({ msg: message || '登录已过期,请重新登录!', duration: 1200 }) |
| | | const timer = setTimeout(() => { |
| | | clearTimeout(timer) |
| | | redirectingToLogin = false |
| | | triggerUnauthorizedRedirect() |
| | | }, 300) |
| | | } |
| | | throw new ApiError(message || '登录已过期,请重新登录!', code, data) |
| | | } |
| | | |
| | | // Handle successful responses |
| | |
| | | // Extract status code and data from UniApp response |
| | | const { statusCode, data } = response as UniNamespace.RequestSuccessCallbackResult |
| | | |
| | | // 处理401/403错误(如果不是在handleAlovaResponse中处理的) |
| | | if ((statusCode === 401 || statusCode === 403)) { |
| | | // 如果是未授权错误,清除用户信息并跳转到登录页 |
| | | globalToast.error({ msg: '登录已过期,请重新登录!', duration: 500 }) |
| | | const timer = setTimeout(() => { |
| | | clearTimeout(timer) |
| | | router.replaceAll({ name: 'login' }) |
| | | }, 500) |
| | | |
| | | throw new ApiError('登录已过期,请重新登录!', statusCode, data) |
| | | if (statusCode === 401 || statusCode === 403) { |
| | | handleUnauthorized('登录已过期,请重新登录!', statusCode, data) |
| | | } |
| | | |
| | | // Handle HTTP error status codes |
| | |
| | | console.log('[Alova Response]', json) |
| | | } |
| | | |
| | | if (json.code === 401 || json.code === 403) { |
| | | handleUnauthorized(json.message, json.code, json) |
| | | } |
| | | |
| | | // Return data for successful responses |
| | | return json |
| | | } |
| | |
| | | console.error('[Alova Error]', error, method) |
| | | } |
| | | |
| | | // 处理401/403错误(如果不是在handleAlovaResponse中处理的) |
| | | if (error instanceof ApiError && (error.code === 401 || error.code === 403)) { |
| | | // 如果是未授权错误,清除用户信息并跳转到登录页 |
| | | globalToast.error({ msg: '登录已过期,请重新登录!', duration: 500 }) |
| | | const timer = setTimeout(() => { |
| | | clearTimeout(timer) |
| | | router.replaceAll({ name: 'login' }) |
| | | }, 500) |
| | | throw new ApiError('登录已过期,请重新登录!', error.code, error.data) |
| | | throw error |
| | | } |
| | | |
| | | // Handle different types of errors |