refactor: 重构异常处理

This commit is contained in:
张传龙 2022-06-17 22:44:32 +08:00
parent f0b6ce7d20
commit ae43ffb94f
6 changed files with 67 additions and 71 deletions

View File

@ -8,7 +8,6 @@
</template>
<script setup>
import { router } from '@/router'
import { useUserStore } from '@/store/modules/user'
import { IconExit } from '@/components/AppIcons'
import { renderIcon } from '@/utils/icon'
@ -32,7 +31,6 @@ function handleSelect(key) {
confirm() {
userStore.logout()
$message.success('已退出登录')
router.push({ path: '/login' })
},
})
}

View File

@ -2,6 +2,7 @@ import { useUserStore } from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
import { NOT_FOUND_ROUTE } from '@/router/routes'
import { getToken, refreshAccessToken, removeToken } from '@/utils/token'
import { toLogin } from '@/utils/auth'
const WHITE_LIST = ['/login', '/redirect']
export function createPermissionGuard(router) {
@ -18,19 +19,18 @@ export function createPermissionGuard(router) {
refreshAccessToken()
next()
} else {
try {
await userStore.getUserInfo()
const accessRoutes = permissionStore.generateRoutes(userStore.role)
accessRoutes.forEach((route) => {
!router.hasRoute(route.name) && router.addRoute(route)
})
router.addRoute(NOT_FOUND_ROUTE)
next({ ...to, replace: true })
} catch (error) {
await userStore.getUserInfo().catch((error) => {
removeToken()
$message.error(error)
next({ path: '/login', query: { ...to.query, redirect: to.path } })
}
toLogin()
$message.error(`${error.code}${error.message}`)
return
})
const accessRoutes = permissionStore.generateRoutes(userStore.role)
accessRoutes.forEach((route) => {
!router.hasRoute(route.name) && router.addRoute(route)
})
router.addRoute(NOT_FOUND_ROUTE)
next({ ...to, replace: true })
}
}
} else {

View File

@ -1,6 +1,7 @@
import { defineStore } from 'pinia'
import { getUser } from '@/api/user'
import { removeToken } from '@/utils/token'
import { toLogin } from '@/utils/auth'
export const useUserStore = defineStore('user', {
state() {
@ -31,14 +32,14 @@ export const useUserStore = defineStore('user', {
this.userInfo = { id, name, avatar, role }
return Promise.resolve(res.data)
} else {
return Promise.reject(res.message)
return Promise.reject(res)
}
} catch (error) {
console.error(error)
return Promise.reject(error.message)
return Promise.reject(error)
}
},
logout() {
toLogin()
removeToken()
this.userInfo = {}
},

8
src/utils/auth.js Normal file
View File

@ -0,0 +1,8 @@
import { router } from '@/router'
export function toLogin() {
router.replace({
path: '/login',
query: { ...router.currentRoute.query, redirect: router.currentRoute.path },
})
}

View File

@ -1,6 +1,6 @@
import { router } from '@/router'
import { getToken, removeToken } from '@/utils/token'
import { isNullOrUndef } from '../is'
import { getToken } from '@/utils/token'
import { toLogin } from '@/utils/auth'
import { isNullOrUndef } from '@/utils/is'
import { isWithoutToken } from './helpers'
export function reqResolve(config) {
@ -15,25 +15,22 @@ export function reqResolve(config) {
}
const token = getToken()
if (token) {
if (!token) {
/**
* * jwt token
* ! 认证方案: Bearer
* * 未登录或者token过期的情况下
* * 跳转登录页重新登录携带当前路由及参数登录成功会回到原来的页面
*/
if (!config.headers.Authorization) config.headers.Authorization = 'Bearer ' + token
return config
toLogin()
return Promise.reject({ code: '-1', message: '未登录' })
}
/**
* * 未登录或者token过期的情况下
* * 跳转登录页重新登录携带当前路由及参数登录成功会回到原来的页面
* * jwt token
* ! 认证方案: Bearer
*/
const { currentRoute } = router
router.replace({
path: '/login',
query: { ...currentRoute.query, redirect: currentRoute.path },
})
return Promise.reject({ code: '-1', message: '未登录' })
config.headers.Authorization = config.headers.Authorization || 'Bearer ' + token
return config
}
export function reqReject(error) {
@ -48,33 +45,27 @@ export function repReject(error) {
let { code, message } = error.response?.data || {}
if (isNullOrUndef(code)) {
// 未知错误
console.error('【err】' + error)
return Promise.reject({ code: -1, message: '接口异常!', error })
code = -1
message = '接口异常!'
} else {
/**
* TODO 此处可以根据后端返回的错误码自定义框架层面的错误处理
*/
switch (code) {
case 401:
message = message || '登录已过期'
break
case 403:
message = message || '没有权限'
break
case 404:
message = message || '资源或接口不存在'
break
default:
message = message || '未知异常'
break
}
}
/**
* TODO 此处可以根据后端返回的错误码自定义框架层面的错误处理
*/
switch (code) {
case 401:
message = message || '未登录'
// * 处理未登录的情况
removeToken()
const { currentRoute } = router
router.replace({
path: '/login',
query: { ...currentRoute.query, redirect: currentRoute.path },
})
break
case 403:
message = message || '没有权限'
// TODO 处理没有权限的情况
break
case 404:
message = message || '资源或接口不存在'
// TODO 处理资源或接口不存在的情况
break
default:
break
}
return Promise.resolve({ code, message })
console.error(`${code}${error}`)
return Promise.resolve({ code, message, error })
}

View File

@ -24,14 +24,12 @@ export async function refreshAccessToken() {
return
}
const { time } = tokenItem
if (new Date().getTime() - time > 1000 * 60 * 30) {
try {
const res = await refreshToken()
if (res.code === 0) {
setToken(res.data.token)
}
} catch (error) {
console.error(error)
// token生成或者刷新后30分钟内不执行刷新
if (new Date().getTime() - time <= 1000 * 60 * 30) return
try {
const res = await refreshToken()
if (res.code === 0) {
setToken(res.data.token)
}
}
} catch (error) {}
}