puzhibing
2026-08-28 e92cd56bb56b111c1afe9922191f9897215ff6b0
yuyueMiniProgram/src/api/core/handlers.ts
@@ -7,7 +7,8 @@
 * @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 {
@@ -25,11 +26,25 @@
// 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 timer = setTimeout(() => {
      clearTimeout(timer)
      redirectingToLogin = false
      triggerUnauthorizedRedirect()
    }, 300)
  }
  throw new ApiError(message || '登录已过期,请重新登录!', code, data)
}
// Handle successful responses
@@ -40,16 +55,8 @@
  // 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
@@ -65,6 +72,10 @@
    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
}
@@ -77,15 +88,8 @@
    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