feat: HTTP状态码 + 业务码

This commit is contained in:
2026-06-24 11:14:27 +08:00
parent 3f6d3f2761
commit 7b3d31a57c
5 changed files with 45 additions and 36 deletions

View File

@@ -58,6 +58,7 @@ class RequestClient {
this.setupInterceptors()
}
// @ts-ignore
/** 注册请求和响应拦截器 */
private setupInterceptors(): void {
// === 请求拦截器 ===
@@ -86,8 +87,8 @@ class RequestClient {
)
// === 通用响应拦截器 ===
// 职责:解包 ApiResponse + 发布非 401 的错误事件
// 401 全部透传,由 refreshInterceptor 统一处理。
// 职责:解包 ApiResponse + 按 HTTP 状态码分类处理错误
// HTTP 401 全部透传,由 refreshInterceptor 统一处理。
this.instance.interceptors.response.use(
// @ts-expect-error 拦截器解包 axiosResponse → ApiResponse
(response) => {
@@ -97,30 +98,41 @@ class RequestClient {
return data
}
// 401 透传给刷新拦截器,此处不处理
if (data.code === 401) {
return response
}
// code !== 0 但 HTTP 2xx — 未改造端点或特殊场景,按业务错误处理
eventBus.emit(AppEvents.REQUEST_ERROR, {
type: 'business',
code: data.code,
httpStatus: response.status,
message: data.message || '请求失败'
})
return Promise.reject(data)
},
(error) => {
const status = error.response?.status
// HTTP 401 透传给刷新拦截器
if (error.response?.status === 401) {
if (status === 401) {
throw error
}
// HTTP 400/403/404/409/405/500 — 从 body 提取 ApiResponse
const body = error.response?.data as ApiResponse | undefined
if (body && status) {
eventBus.emit(AppEvents.REQUEST_ERROR, {
type: 'business',
code: body.code,
httpStatus: status,
message: body.message || `请求错误 (${status})`
})
return Promise.reject(body)
}
// 网络异常(无 response
eventBus.emit(AppEvents.REQUEST_ERROR, {
type: error.response ? 'http' : 'network',
code: error.response?.status,
message: error.response
? `请求错误 (${error.response.status})`
: '网络异常,请检查网络连接'
code: status,
httpStatus: status,
message: error.response ? `请求错误 (${status})` : '网络异常,请检查网络连接'
})
return Promise.reject(error)
}
@@ -150,7 +162,7 @@ class RequestClient {
},
refreshTokenQueue: this.refreshTokenQueue
})
// @ts-expect-error 拦截器解包 axiosResponse → ApiResponse
// 拦截器解包 axiosResponse → ApiResponse
this.instance.interceptors.response.use(onFulfilled, onRejected)
}