refactor: 优化401/403错误处理逻辑,更符合常理

核心改进:
- 401错误:先尝试刷新token,刷新成功则标记后返回null交由上层重试
- 403错误:直接跳转到登录页
- 移除无用的options和httpClient参数
- 简化层次:client.js(清理) -> http.js(业务) -> AuthService(刷新)

具体变更:
1. client.js: handle401Error()只清空token,不处理重定向
2. http.js:
   - 401优先尝试刷新,失败才跳转登录页
   - 403直接跳转登录页
3. AuthService.js:
   - 刷新成功:标记error._handled=true, error._tokenRefreshed=true,返回null
   - 刷新失败:调用回调后抛出错误,交由上层处理跳转
   - 移除options和httpClient参数

逻辑更清晰:client清理token -> http处理逻辑 -> AuthService刷新token,职责分明

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-25 01:03:20 +08:00
parent a32f118281
commit c9fb224936
4 changed files with 45 additions and 31 deletions

View File

@@ -21,28 +21,31 @@ export function createHttpClient(options = {}) {
const httpClient = createClientAxios({
baseURL: '/',
timeout: 180000,
on401: (error) => {
on401: async (error) => {
// 401优先使用上层自定义处理
if (on401) {
on401(error)
} else {
// 默认使用 AuthService 处理,并传入 httpClient 确保拦截器生效
authService.handleAuthError(
error,
() => window.location.href = '/login',
{ httpClient } // 关键:传入 HTTP 实例
)
await on401(error)
return
}
// 默认处理:使用 AuthService 尝试刷新token
await authService.handleAuthError(
error,
() => {
// 刷新失败,跳转到登录页
window.location.href = '/login'
}
)
// 如果刷新成功AuthService返回null不跳转不抛出错误
// 业务代码可以捕获这个错误并重试请求
},
on403: (error) => {
// 403没有权限直接跳转到登录页
if (on403) {
on403(error)
} else {
// 默认使用 AuthService 处理,并传入 httpClient 确保拦截器生效
authService.handleAuthError(
error,
() => window.location.href = '/login',
{ httpClient } // 关键:传入 HTTP 实例
)
console.warn('403权限不足跳转到登录页')
window.location.href = '/login'
}
},
})