@kevairy/template 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/package.json +1 -1
  2. package/template/.env +2 -5
  3. package/template/.env.production +6 -0
  4. package/template/README.md +12 -0
  5. package/template/package.json +5 -5
  6. package/template/scripts/build-info.ts +76 -0
  7. package/template/src/adapters/auth/index.ts +1 -1
  8. package/template/src/adapters/auth/types.ts +6 -1
  9. package/template/src/api/auth.ts +3 -2
  10. package/template/src/components/core/layouts/art-guide/index.vue +9 -1
  11. package/template/src/components/core/layouts/art-page-content/index.vue +8 -1
  12. package/template/src/config/index.ts +4 -0
  13. package/template/src/directives/core/access.ts +125 -0
  14. package/template/src/directives/core/auth.ts +7 -62
  15. package/template/src/directives/core/roles.ts +5 -83
  16. package/template/src/env.d.ts +2 -0
  17. package/template/src/hooks/core/useAuth.ts +2 -74
  18. package/template/src/hooks/core/useGuide.ts +6 -0
  19. package/template/src/hooks/core/usePermission.ts +41 -0
  20. package/template/src/hooks/index.ts +1 -0
  21. package/template/src/locales/langs/en.json +11 -1
  22. package/template/src/locales/langs/zh.json +11 -1
  23. package/template/src/main.ts +18 -10
  24. package/template/src/router/core/IframeRouteManager.ts +4 -2
  25. package/template/src/router/core/MenuProcessor.ts +5 -40
  26. package/template/src/router/core/RoutePermissionValidator.ts +6 -149
  27. package/template/src/router/core/access.ts +79 -0
  28. package/template/src/router/guards/afterEach.ts +6 -10
  29. package/template/src/router/guards/beforeEach.ts +143 -100
  30. package/template/src/router/guards/error.ts +42 -0
  31. package/template/src/router/index.ts +2 -0
  32. package/template/src/router/modules/examples.ts +4 -3
  33. package/template/src/router/routes/staticRoutes.ts +5 -3
  34. package/template/src/services/auth.ts +32 -10
  35. package/template/src/services/permission.ts +21 -0
  36. package/template/src/store/modules/menu.ts +28 -8
  37. package/template/src/store/modules/user.ts +72 -35
  38. package/template/src/store/modules/worktab.ts +1 -1
  39. package/template/src/types/api/api.d.ts +4 -1
  40. package/template/src/types/build-info.ts +11 -0
  41. package/template/src/types/config/index.ts +5 -2
  42. package/template/src/types/directive/directive.d.ts +1 -0
  43. package/template/src/types/router/index.ts +6 -0
  44. package/template/src/utils/http/contract.ts +51 -19
  45. package/template/src/utils/http/error.ts +73 -26
  46. package/template/src/utils/http/index.ts +160 -167
  47. package/template/src/utils/http/request-manager.ts +124 -0
  48. package/template/src/utils/http/status.ts +1 -0
  49. package/template/src/utils/permission/index.ts +66 -0
  50. package/template/src/utils/session.ts +24 -0
  51. package/template/src/utils/storage/storage-config.ts +15 -0
  52. package/template/src/utils/storage/storage.ts +5 -3
  53. package/template/src/utils/sys/console.ts +63 -7
  54. package/template/src/utils/sys/diagnostics.ts +180 -0
  55. package/template/src/utils/sys/error-handle.ts +56 -126
  56. package/template/src/utils/sys/recovery.ts +31 -0
  57. package/template/src/views/examples/permissions/index.vue +69 -13
  58. package/template/src/views/exception/403/index.vue +33 -0
  59. package/template/src/views/exception/500/index.vue +52 -10
  60. package/template/tests/e2e/permissions.spec.ts +53 -0
  61. package/template/tests/e2e/session-recovery.spec.ts +49 -0
  62. package/template/tests/unit/build/build-info.spec.ts +151 -0
  63. package/template/tests/unit/diagnostics/diagnostics.spec.ts +132 -0
  64. package/template/tests/unit/diagnostics/router.spec.ts +84 -0
  65. package/template/tests/unit/http/auth-lifecycle.spec.ts +203 -0
  66. package/template/tests/unit/http/contract.spec.ts +46 -0
  67. package/template/tests/unit/http/request.spec.ts +487 -0
  68. package/template/tests/unit/permissions/guard.spec.ts +261 -0
  69. package/template/tests/unit/permissions/guide.spec.ts +30 -0
  70. package/template/tests/unit/permissions/rules.spec.ts +106 -0
  71. package/template/tests/unit/permissions/state-and-directives.spec.ts +176 -0
  72. package/template/tests/unit/router/examples.spec.ts +5 -1
  73. package/template/tsconfig.json +8 -1
  74. package/template/vite.config.ts +19 -9
@@ -43,6 +43,13 @@ import { resetRouterState } from '@/router/guards/beforeEach'
43
43
  import { useMenuStore } from './menu'
44
44
  import { useLockStore } from './lock'
45
45
  import { StorageConfig } from '@/utils/storage/storage-config'
46
+ import { normalizeGrants } from '@/utils/permission'
47
+ import {
48
+ cancelAllPendingRequests,
49
+ closeSessionRequests,
50
+ invalidateSessionRequests
51
+ } from '@/utils/http/request-manager'
52
+ import { runSessionCleanups } from '@/utils/session'
46
53
 
47
54
  /**
48
55
  * 用户状态管理
@@ -55,8 +62,16 @@ export const useUserStore = defineStore(
55
62
  const language = ref(LanguageEnum.ZH)
56
63
  // 登录状态
57
64
  const isLogin = ref(false)
65
+ const isSigningOut = ref(false)
66
+ const sessionEpoch = ref(0)
58
67
  // 用户信息
59
68
  const info = ref<Partial<Api.Auth.UserInfo>>({})
69
+ // 不持久化授权和加载状态,刷新后必须重新获取。
70
+ const permissionsReady = ref(false)
71
+ const permissions = computed(() =>
72
+ normalizeGrants(info.value.permissions ?? info.value.buttons)
73
+ )
74
+ const roles = computed(() => normalizeGrants(info.value.roles))
60
75
  // 搜索历史记录
61
76
  const searchHistory = ref<AppRouteRecord[]>([])
62
77
  // 访问令牌
@@ -76,7 +91,14 @@ export const useUserStore = defineStore(
76
91
  * @param newInfo 新的用户信息
77
92
  */
78
93
  const setUserInfo = (newInfo: Api.Auth.UserInfo) => {
79
- info.value = newInfo
94
+ const grants = normalizeGrants(newInfo.permissions ?? newInfo.buttons)
95
+ info.value = {
96
+ ...newInfo,
97
+ permissions: grants,
98
+ buttons: grants,
99
+ roles: normalizeGrants(newInfo.roles)
100
+ }
101
+ permissionsReady.value = true
80
102
  }
81
103
 
82
104
  /**
@@ -110,12 +132,41 @@ export const useUserStore = defineStore(
110
132
  * @param newRefreshToken 刷新令牌(可选)
111
133
  */
112
134
  const setToken = (newAccessToken: string, newRefreshToken?: string) => {
135
+ if (newAccessToken !== accessToken.value) cancelAllPendingRequests()
113
136
  accessToken.value = newAccessToken
114
137
  refreshToken.value = newRefreshToken || ''
115
138
  }
116
139
 
117
- /** 建立已认证会话。 */
140
+ const resetSessionData = () => {
141
+ const currentUserId = info.value.userId
142
+ if (currentUserId !== undefined && currentUserId !== null) {
143
+ localStorage.setItem(StorageConfig.LAST_USER_ID_KEY, String(currentUserId))
144
+ }
145
+ sessionEpoch.value++
146
+ info.value = {}
147
+ permissionsReady.value = false
148
+ searchHistory.value = []
149
+ // 列表等待身份确认后恢复;页面实例、当前页和缓存排除表不跨会话。
150
+ const worktabs = useWorktabStore()
151
+ worktabs.current = {}
152
+ worktabs.keepAliveExclude = []
153
+ useMenuStore().setHomePath('')
154
+ useLockStore().reset()
155
+ resetRouterState(0)
156
+ runSessionCleanups()
157
+ }
158
+
159
+ const beginSignOut = () => {
160
+ closeSessionRequests()
161
+ isSigningOut.value = true
162
+ resetRouterState(0)
163
+ }
164
+
165
+ /** 建立已认证会话,直接切换账号也经过完整的缓存边界。 */
118
166
  const establishSession = (newAccessToken: string, newRefreshToken?: string) => {
167
+ invalidateSessionRequests()
168
+ resetSessionData()
169
+ isSigningOut.value = false
119
170
  setToken(newAccessToken, newRefreshToken)
120
171
  setLoginStatus(true)
121
172
  }
@@ -125,29 +176,15 @@ export const useUserStore = defineStore(
125
176
  * 如果是同一账号重新登录,保留工作台标签页
126
177
  */
127
178
  const clearAuthState = (redirectToLogin = true) => {
128
- // 保存当前用户 ID,用于下次登录时判断是否为同一用户
129
- const currentUserId = info.value.userId
130
- if (currentUserId) {
131
- localStorage.setItem(StorageConfig.LAST_USER_ID_KEY, String(currentUserId))
132
- }
133
-
134
- // 清空用户信息
135
- info.value = {}
179
+ invalidateSessionRequests()
180
+ resetSessionData()
181
+ isSigningOut.value = false
136
182
  // 重置登录状态
137
183
  isLogin.value = false
138
184
  // 清空访问令牌
139
185
  accessToken.value = ''
140
186
  // 清空刷新令牌
141
187
  refreshToken.value = ''
142
- // 注意:不清空工作台标签页,等下次登录时根据用户判断
143
- // 移除iframe路由缓存
144
- sessionStorage.removeItem('iframeRoutes')
145
- // 清空主页路径
146
- useMenuStore().setHomePath('')
147
- // 解除锁屏状态并清除独立锁屏密码,避免下次登录被遗留的锁定态拦截
148
- useLockStore().reset()
149
- // 重置路由状态
150
- resetRouterState(500)
151
188
  if (!redirectToLogin) return
152
189
 
153
190
  // 跳转到登录页,携带当前路由作为 redirect 参数
@@ -171,29 +208,28 @@ export const useUserStore = defineStore(
171
208
  const lastUserId = localStorage.getItem(StorageConfig.LAST_USER_ID_KEY)
172
209
  const currentUserId = info.value.userId
173
210
 
174
- // 无法获取当前用户 ID,跳过检查
175
- if (!currentUserId) return
176
-
177
- // 首次登录或缓存已清除,保留现有标签页
178
- if (!lastUserId) {
179
- return
180
- }
181
-
182
- // 不同用户登录,清空工作台标签页
183
- if (String(currentUserId) !== lastUserId) {
184
- const worktabStore = useWorktabStore()
185
- worktabStore.opened = []
186
- worktabStore.keepAliveExclude = []
211
+ // 来源不明或不同账号的持久化标签不恢复;数字 0 也是有效 ID。
212
+ if (
213
+ currentUserId === undefined ||
214
+ currentUserId === null ||
215
+ lastUserId !== String(currentUserId)
216
+ ) {
217
+ useWorktabStore().clearAll()
187
218
  }
188
-
189
- // 清除临时存储
190
- localStorage.removeItem(StorageConfig.LAST_USER_ID_KEY)
219
+ if (currentUserId !== undefined && currentUserId !== null) {
220
+ localStorage.setItem(StorageConfig.LAST_USER_ID_KEY, String(currentUserId))
221
+ } else localStorage.removeItem(StorageConfig.LAST_USER_ID_KEY)
191
222
  }
192
223
 
193
224
  return {
194
225
  language,
195
226
  isLogin,
227
+ isSigningOut,
228
+ sessionEpoch,
196
229
  info,
230
+ permissionsReady,
231
+ permissions,
232
+ roles,
197
233
  searchHistory,
198
234
  accessToken,
199
235
  refreshToken,
@@ -206,6 +242,7 @@ export const useUserStore = defineStore(
206
242
  setSearchHistory,
207
243
  setToken,
208
244
  establishSession,
245
+ beginSignOut,
209
246
  clearAuthState,
210
247
  logOut,
211
248
  checkAndClearWorktabs
@@ -446,7 +446,7 @@ export const useWorktabStore = defineStore(
446
446
  path: tab.path,
447
447
  query: (tab.query as LocationQueryRaw) || undefined
448
448
  })
449
- return resolved.matched.length > 0
449
+ return resolved.matched.length > 0 && resolved.name !== 'Exception404'
450
450
  }
451
451
  return false
452
452
  } catch {
@@ -75,7 +75,10 @@ declare namespace Api {
75
75
 
76
76
  /** 用户信息 */
77
77
  interface UserInfo {
78
- buttons: string[]
78
+ /** 标准操作权限集合;显式空数组表示没有操作权限。 */
79
+ permissions?: string[]
80
+ /** 兼容旧认证适配器,仅在未提供 permissions 时作为输入。 */
81
+ buttons?: string[]
79
82
  roles: string[]
80
83
  userId: number | string
81
84
  userName: string
@@ -0,0 +1,11 @@
1
+ /** 当前页面所加载产物的构建信息,所有字段均可公开。 */
2
+ export interface BuildInfo {
3
+ version: string
4
+ buildId: string
5
+ gitCommit: string | null
6
+ /** null 表示无法确认工作区状态(例如没有 Git 或由 CI 仅注入提交号)。 */
7
+ gitDirty: boolean | null
8
+ builtAt: string
9
+ /** Vite 构建模式,不代表实际部署环境。 */
10
+ mode: string
11
+ }
@@ -95,6 +95,10 @@ export interface AppNavigationConfig {
95
95
  titleTemplate: string
96
96
  }
97
97
 
98
+ export interface AppAccessControlConfig {
99
+ wildcardPermission: string | false
100
+ }
101
+
98
102
  export interface AppFeatureConfig {
99
103
  menuButton: boolean
100
104
  refreshButton: boolean
@@ -169,6 +173,7 @@ export interface FastEnterConfig {
169
173
  export interface SystemConfig {
170
174
  // 系统基础信息
171
175
  systemInfo: SystemBasicConfig
176
+ accessControl: AppAccessControlConfig
172
177
  navigation: AppNavigationConfig
173
178
  features: AppFeatureConfig
174
179
  storage: AppStorageConfig
@@ -194,8 +199,6 @@ export interface SystemConfig {
194
199
  export interface EnvConfig {
195
200
  // 环境名称
196
201
  NODE_ENV: string
197
- // 应用版本
198
- VITE_VERSION: string
199
202
  // 应用端口
200
203
  VITE_PORT: string
201
204
  // 应用基础路径
@@ -8,6 +8,7 @@ import type {
8
8
  declare module 'vue' {
9
9
  export interface GlobalDirectives {
10
10
  vAuth: AuthDirective
11
+ vPermission: AuthDirective
11
12
  vRoles: RolesDirective
12
13
  vRipple: RippleDirective
13
14
  vHighlight: HighlightDirective
@@ -27,6 +27,8 @@ import { RouteRecordRaw } from 'vue-router'
27
27
  * 定义路由的各种配置属性
28
28
  */
29
29
  export interface RouteMeta extends Record<string | number | symbol, unknown> {
30
+ /** 静态路由是否要求认证;动态路由始终要求认证。 */
31
+ requiresAuth?: boolean
30
32
  /** 路由标题 */
31
33
  title: string
32
34
  /** 路由图标 */
@@ -54,6 +56,10 @@ export interface RouteMeta extends Record<string | number | symbol, unknown> {
54
56
  isFirstLevel?: boolean
55
57
  /** 角色权限 */
56
58
  roles?: string[]
59
+ /** 进入页面所需的操作权限,与 authList 的动作描述分离。 */
60
+ permissions?: string[]
61
+ /** permissions 默认满足任一项;all 表示全部满足。 */
62
+ permissionMode?: 'any' | 'all'
57
63
  /** 是否固定标签页 */
58
64
  fixedTab?: boolean
59
65
  /** 激活菜单路径 */
@@ -13,27 +13,59 @@ export function isApiSuccessCode(code: number): boolean {
13
13
  return code === 0 || code === ApiStatus.success
14
14
  }
15
15
 
16
+ /** 类型标签和 JSON 转义避免分隔符碰撞。非 JSON 数据不参与自动去重。 */
16
17
  export function stableSerialize(payload: unknown): string {
17
- if (payload === undefined || payload === null) return ''
18
- if (typeof payload !== 'object') return String(payload)
19
- if (payload instanceof FormData || payload instanceof Blob || payload instanceof ArrayBuffer) {
20
- return payload.constructor.name
18
+ const ancestors = new WeakSet<object>()
19
+ const encode = (value: unknown): unknown => {
20
+ if (value === null) return ['null']
21
+ if (value === undefined) return ['undefined']
22
+ if (typeof value === 'string' || typeof value === 'boolean') return [typeof value, value]
23
+ if (typeof value === 'number') return ['number', Object.is(value, -0) ? '-0' : String(value)]
24
+ if (typeof value !== 'object') throw new TypeError('Unsupported request-key value')
25
+ const prototype = Object.getPrototypeOf(value)
26
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {
27
+ throw new TypeError('Only plain JSON data can be automatically deduplicated')
28
+ }
29
+ if (ancestors.has(value)) throw new TypeError('Circular request-key value')
30
+ ancestors.add(value)
31
+ try {
32
+ if (Array.isArray(value)) {
33
+ return [
34
+ 'array',
35
+ Array.from({ length: value.length }, (_, index) =>
36
+ Object.hasOwn(value, index) ? encode(value[index]) : ['hole']
37
+ )
38
+ ]
39
+ }
40
+ return [
41
+ 'object',
42
+ Object.keys(value)
43
+ .sort()
44
+ .map((key) => [key, encode((value as Record<string, unknown>)[key])])
45
+ ]
46
+ } finally {
47
+ ancestors.delete(value)
48
+ }
21
49
  }
22
-
23
- if (Array.isArray(payload)) return `[${payload.map(stableSerialize).join(',')}]`
24
-
25
- return `{${Object.entries(payload as Record<string, unknown>)
26
- .sort(([left], [right]) => left.localeCompare(right))
27
- .map(([key, value]) => `${key}:${stableSerialize(value)}`)
28
- .join(',')}}`
50
+ return JSON.stringify(encode(payload))
29
51
  }
30
52
 
31
- /** 为重复请求取消生成与对象属性顺序无关的稳定键。 */
32
- export function createRequestKey(config: AxiosRequestConfig): string {
33
- return [
34
- config.method?.toUpperCase() || 'GET',
35
- config.url || '',
36
- stableSerialize(config.params),
37
- stableSerialize(config.data)
38
- ].join('|')
53
+ /** 不支持可靠比较的数据返回 undefined,跳过去重但照常发送请求。 */
54
+ export function createRequestKey(config: AxiosRequestConfig): string | undefined {
55
+ if (config.paramsSerializer || config.transformRequest) return undefined
56
+ try {
57
+ return stableSerialize({
58
+ method: config.method?.toUpperCase() || 'GET',
59
+ baseURL: config.baseURL ?? '',
60
+ url: config.url ?? '',
61
+ params: config.params,
62
+ data: config.data,
63
+ responseType: config.responseType ?? 'json',
64
+ auth: config.auth,
65
+ withCredentials: config.withCredentials,
66
+ headers: config.headers
67
+ })
68
+ } catch {
69
+ return undefined
70
+ }
39
71
  }
@@ -21,9 +21,13 @@
21
21
  * @module utils/http/error
22
22
  * @author Art Design Pro Team
23
23
  */
24
- import { AxiosError } from 'axios'
24
+ import { isAxiosError, isCancel } from 'axios'
25
+ import { ElMessage } from 'element-plus'
25
26
  import { ApiStatus } from './status'
26
27
  import { $t } from '@/locales'
28
+ import { reportDiagnostic } from '@/utils/sys/diagnostics'
29
+
30
+ export type HttpErrorKind = 'business' | 'http' | 'network' | 'timeout' | 'cancelled' | 'config'
27
31
 
28
32
  // 错误响应接口
29
33
  export interface ErrorResponse {
@@ -37,6 +41,7 @@ export interface ErrorResponse {
37
41
 
38
42
  // 错误日志数据接口
39
43
  export interface ErrorLogData {
44
+ kind?: HttpErrorKind
40
45
  /** 错误状态码 */
41
46
  code: number
42
47
  /** 错误消息 */
@@ -55,6 +60,7 @@ export interface ErrorLogData {
55
60
 
56
61
  // 自定义 HttpError 类
57
62
  export class HttpError extends Error {
63
+ public readonly kind: HttpErrorKind
58
64
  public readonly code: number
59
65
  public readonly data?: unknown
60
66
  public readonly timestamp: string
@@ -65,6 +71,7 @@ export class HttpError extends Error {
65
71
  message: string,
66
72
  code: number,
67
73
  options?: {
74
+ kind?: HttpErrorKind
68
75
  data?: unknown
69
76
  url?: string
70
77
  method?: string
@@ -73,6 +80,7 @@ export class HttpError extends Error {
73
80
  super(message)
74
81
  this.name = 'HttpError'
75
82
  this.code = code
83
+ this.kind = options?.kind ?? 'business'
76
84
  this.data = options?.data
77
85
  this.timestamp = new Date().toISOString()
78
86
  this.url = options?.url
@@ -82,6 +90,7 @@ export class HttpError extends Error {
82
90
  public toLogData(): ErrorLogData {
83
91
  return {
84
92
  code: this.code,
93
+ kind: this.kind,
85
94
  message: this.message,
86
95
  data: this.data,
87
96
  timestamp: this.timestamp,
@@ -118,36 +127,69 @@ const getErrorMessage = (status: number): string => {
118
127
  * @param error 错误对象
119
128
  * @returns 错误对象
120
129
  */
121
- export function handleError(error: AxiosError<ErrorResponse>): never {
122
- // 处理取消的请求
123
- if (error.code === 'ERR_CANCELED') {
124
- console.warn('Request cancelled:', error.message)
125
- throw new HttpError($t('httpMsg.requestCancelled'), ApiStatus.error)
130
+ export function toHttpError(error: unknown): HttpError {
131
+ if (error instanceof HttpError) return error
132
+ const axiosError = isAxiosError<ErrorResponse & { message?: string }>(error) ? error : undefined
133
+ const context = {
134
+ url: axiosError?.config?.url,
135
+ method: axiosError?.config?.method?.toUpperCase()
126
136
  }
127
-
128
- const statusCode = error.response?.status
129
- const errorMessage = error.response?.data?.msg || error.message
130
- const requestConfig = error.config
131
-
132
- // 处理网络错误
133
- if (!error.response) {
134
- throw new HttpError($t('httpMsg.networkError'), ApiStatus.error, {
135
- url: requestConfig?.url,
136
- method: requestConfig?.method?.toUpperCase()
137
+ if (
138
+ isCancel(error) ||
139
+ axiosError?.code === 'ERR_CANCELED' ||
140
+ (error instanceof Error && error.name === 'AbortError')
141
+ ) {
142
+ return new HttpError($t('httpMsg.requestCancelled'), ApiStatus.requestCancelled, {
143
+ ...context,
144
+ kind: 'cancelled'
137
145
  })
138
146
  }
139
-
140
- // 处理 HTTP 状态码错误
141
- const message = statusCode
142
- ? getErrorMessage(statusCode)
143
- : errorMessage || $t('httpMsg.requestFailed')
144
- throw new HttpError(message, statusCode || ApiStatus.error, {
145
- data: error.response.data,
146
- url: requestConfig?.url,
147
- method: requestConfig?.method?.toUpperCase()
147
+ if (axiosError?.response) {
148
+ const status = axiosError.response.status
149
+ return new HttpError(getErrorMessage(status), status, {
150
+ ...context,
151
+ kind: 'http',
152
+ data: axiosError.response.data
153
+ })
154
+ }
155
+ if (axiosError?.code === 'ECONNABORTED' || axiosError?.code === 'ETIMEDOUT') {
156
+ return new HttpError($t('httpMsg.requestTimeout'), ApiStatus.requestTimeout, {
157
+ ...context,
158
+ kind: 'timeout'
159
+ })
160
+ }
161
+ if (
162
+ axiosError &&
163
+ (axiosError.request ||
164
+ ['ERR_NETWORK', 'ENOTFOUND', 'ECONNRESET', 'ECONNREFUSED', 'EAI_AGAIN'].includes(
165
+ axiosError.code ?? ''
166
+ ))
167
+ ) {
168
+ return new HttpError($t('httpMsg.networkError'), ApiStatus.error, {
169
+ ...context,
170
+ kind: 'network'
171
+ })
172
+ }
173
+ return new HttpError($t('httpMsg.requestConfigError'), ApiStatus.error, {
174
+ ...context,
175
+ kind: 'config'
148
176
  })
149
177
  }
150
178
 
179
+ /** 兼容已有调用:转换后抛出统一错误。 */
180
+ export function handleError(error: unknown): never {
181
+ throw toHttpError(error)
182
+ }
183
+
184
+ export function isRequestCanceled(error: unknown): boolean {
185
+ return (
186
+ (error instanceof HttpError && error.kind === 'cancelled') ||
187
+ isCancel(error) ||
188
+ (isAxiosError(error) && error.code === 'ERR_CANCELED') ||
189
+ (error instanceof Error && error.name === 'AbortError')
190
+ )
191
+ }
192
+
151
193
  /**
152
194
  * 显示错误消息
153
195
  * @param error 错误对象
@@ -158,7 +200,12 @@ export function showError(error: HttpError, showMessage: boolean = true): void {
158
200
  ElMessage.error(error.message)
159
201
  }
160
202
  // 记录错误日志
161
- console.error('[HTTP Error]', error.toLogData())
203
+ reportDiagnostic('http', error, {
204
+ code: error.code,
205
+ errorKind: error.kind,
206
+ url: error.url,
207
+ method: error.method
208
+ })
162
209
  }
163
210
 
164
211
  /**