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> </template>
<script setup> <script setup>
import { router } from '@/router'
import { useUserStore } from '@/store/modules/user' import { useUserStore } from '@/store/modules/user'
import { IconExit } from '@/components/AppIcons' import { IconExit } from '@/components/AppIcons'
import { renderIcon } from '@/utils/icon' import { renderIcon } from '@/utils/icon'
@ -32,7 +31,6 @@ function handleSelect(key) {
confirm() { confirm() {
userStore.logout() userStore.logout()
$message.success('已退出登录') $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 { usePermissionStore } from '@/store/modules/permission'
import { NOT_FOUND_ROUTE } from '@/router/routes' import { NOT_FOUND_ROUTE } from '@/router/routes'
import { getToken, refreshAccessToken, removeToken } from '@/utils/token' import { getToken, refreshAccessToken, removeToken } from '@/utils/token'
import { toLogin } from '@/utils/auth'
const WHITE_LIST = ['/login', '/redirect'] const WHITE_LIST = ['/login', '/redirect']
export function createPermissionGuard(router) { export function createPermissionGuard(router) {
@ -18,19 +19,18 @@ export function createPermissionGuard(router) {
refreshAccessToken() refreshAccessToken()
next() next()
} else { } else {
try { await userStore.getUserInfo().catch((error) => {
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) {
removeToken() removeToken()
$message.error(error) toLogin()
next({ path: '/login', query: { ...to.query, redirect: to.path } }) $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 { } else {

View File

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

View File

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