refactor: request error tip

This commit is contained in:
张传龙 2022-09-04 11:35:30 +08:00
parent 3a38adc71e
commit f1bc9edbac
14 changed files with 97 additions and 98 deletions

View File

@ -2,5 +2,5 @@ import request from '@/utils/http'
export default {
getUser: () => request.get('/user'),
refreshToken: () => request.post('/auth/refreshToken'),
refreshToken: () => request.post('/auth/refreshToken', null, { noNeedTip: true }),
}

View File

@ -93,7 +93,6 @@ async function handleQuery() {
} catch (error) {
tableData.value = []
pagination.itemCount = 0
$message.error(error.message)
} finally {
loading.value = false
}
@ -103,7 +102,11 @@ function handleSearch() {
handleQuery()
}
async function handleReset() {
emit('update:queryItems', { ...initQuery })
const queryItems = { ...props.queryItems }
for (const key in queryItems) {
queryItems[key] = ''
}
emit('update:queryItems', { ...queryItems, ...initQuery })
await nextTick()
pagination.page = 1
handleQuery()

View File

@ -1,4 +1,4 @@
import { isNullOrWhitespace } from '../utils/is'
import { isNullOrWhitespace } from '@/utils/is'
const ACTIONS = {
view: '查看',
@ -62,7 +62,6 @@ export default function ({ name, initForm = {}, doCreate, doDelete, doUpdate, re
modalLoading.value = modalVisible.value = false
data && refresh(data)
} catch (error) {
$message.error('操作失败')
modalLoading.value = false
}
})

View File

@ -1,11 +1,10 @@
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'
import { getToken, refreshAccessToken } from '@/utils/token'
import { isNullOrWhitespace } from '@/utils/is'
const WHITE_LIST = ['/login']
const WHITE_LIST = ['/login', '/404']
export function createPermissionGuard(router) {
const userStore = useUserStore()
const permissionStore = usePermissionStore()
@ -19,24 +18,25 @@ export function createPermissionGuard(router) {
}
/** 有token的情况 */
if (to.path === '/login') return { path: '/', replace: true }
if (to.path === '/404') return true
// 已经拿到用户信息
if (userStore.userId) {
refreshAccessToken()
return true
}
await userStore.getUserInfo().catch((error) => {
removeToken()
toLogin()
$message.error(error.message || '获取用户信息失败!')
})
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)
return { ...to, replace: true }
} catch (error) {
console.error(error)
return
}
})
}

View File

@ -27,13 +27,9 @@ export const useUserStore = defineStore('user', {
async getUserInfo() {
try {
const res = await api.getUser()
if (res.code === 0) {
const { id, name, avatar, role } = res.data
this.userInfo = { id, name, avatar, role }
return Promise.resolve(res.data)
} else {
return Promise.reject(res)
}
} catch (error) {
return Promise.reject(error)
}

View File

@ -6,3 +6,9 @@ export function toLogin() {
query: { ...router.currentRoute.value.query, redirect: router.currentRoute.value.path },
})
}
export function toFourZeroFour() {
router.replace({
path: '/404',
})
}

View File

@ -9,7 +9,7 @@ export function setupMessage(NMessage) {
* * loading message不会自动清除除非被替换成非loading message非loading message默认2秒后自动清除
*/
removeMessage(message, duration = 2000) {
removeMessage(message = loadingMessage, duration = 2000) {
setTimeout(() => {
if (message) {
message.destroy()

View File

@ -1,4 +1,7 @@
import { useUserStore } from '@/store/modules/user'
import { isNullOrUndef } from '@/utils/is'
import { removeToken } from '@/utils/token'
import { toLogin } from '@/utils/auth'
const WITHOUT_TOKEN_API = [{ url: '/auth/login', method: 'POST' }]
@ -11,3 +14,36 @@ export function addBaseParams(params) {
params.userId = useUserStore().userId
}
}
export function resolveResError(error = {}) {
let { code, message } = error
if (isNullOrUndef(code)) {
// 未知错误
code = -1
message = message ?? '接口未知异常!'
} else {
switch (code) {
case 400:
message = message ?? '请求参数错误'
break
case 401:
message = message ?? '登录已过期'
removeToken()
toLogin()
break
case 403:
message = message ?? '没有权限'
break
case 404:
message = message ?? '资源或接口不存在'
break
case 500:
message = message ?? '服务器异常'
break
default:
message = message ?? '操作异常!'
break
}
}
return { code, message }
}

View File

@ -1,14 +1,8 @@
import { getToken } from '@/utils/token'
import { toLogin } from '@/utils/auth'
import { isNullOrUndef } from '@/utils/is'
import { isWithoutToken } from './helpers'
import { isWithoutToken, resolveResError } from './helpers'
export function reqResolve(config) {
// 防止缓存给get请求加上时间戳
if (config.method === 'get') {
config.params = { ...config.params, t: new Date().getTime() }
}
// 处理不需要token的请求
if (isWithoutToken(config)) {
return config
@ -35,42 +29,18 @@ export function reqReject(error) {
}
export function repResolve(response) {
if (response?.data?.code !== 0) {
$message.error(response?.data?.message || '操作异常')
return Promise.reject(response?.data)
const { noNeedTip } = response.config
if (response.data?.code !== 0) {
const { code, message } = resolveResError(response?.data)
!noNeedTip && $message.error(message)
return Promise.reject({ code, message, error: response?.data })
}
return Promise.resolve(response?.data)
}
export function repReject(error) {
let { code, message } = error.response?.data || {}
if (isNullOrUndef(code)) {
// 未知错误
code = -1
message = '接口异常!'
} else {
/**
* TODO 此处可以根据后端返回的错误码自定义框架层面的错误处理
*/
switch (code) {
case 400:
message = message || '请求参数错误'
break
case 401:
message = message || '登录已过期'
break
case 403:
message = message || '没有权限'
break
case 404:
message = message || '资源或接口不存在'
break
default:
message = message || '未知异常'
break
}
}
console.error(`${code}${error}`)
$message.error(message || '操作异常')
const { noNeedTip } = error.response?.config || error.config
const { code, message } = resolveResError(error.response?.data)
!noNeedTip && $message.error(message)
return Promise.reject({ code, message, error })
}

View File

@ -26,8 +26,6 @@ export async function refreshAccessToken() {
if (new Date().getTime() - time <= 1000 * 60 * 30) return
try {
const res = await api.refreshToken()
if (res.code === 0) {
setToken(res.data.token)
}
} catch (error) {}
}

View File

@ -5,5 +5,5 @@ export default {
getPostById: (id) => request.get(`/post/${id}`),
addPost: (data) => request.post('/post', data),
updatePost: (data) => request.put(`/post/${data.id}`, data),
deletePost: (id) => request.delete(`/post/${id}`),
deletePost: (id) => request.delete(`/post/${id}`, null),
}

View File

@ -90,9 +90,7 @@ import { isNullOrUndef } from '@/utils/is'
const $table = ref(null)
/** QueryBar筛选参数可选 */
const queryItems = ref({
title: '',
})
const queryItems = ref({})
/** 补充参数(可选) */
const extraParams = ref({})

View File

@ -163,12 +163,8 @@ export const usePostTable = () => {
async function getTableData() {
try {
const res = await api.getPosts()
if (res.code === 0) {
return res.data
}
console.warn(res.message)
return []
const { data } = await api.getPosts()
return data
} catch (error) {
console.error(error)
return []

View File

@ -81,10 +81,9 @@ async function handleLogin() {
return
}
try {
$message.loading('正在验证...')
loging.value = true
$message.loading('正在验证...')
const res = await api.login({ name, password: password.toString() })
if (res.code === 0) {
$message.success('登录成功')
setToken(res.data.token)
if (isRemember.value) {
@ -99,11 +98,9 @@ async function handleLogin() {
} else {
router.push('/')
}
} else {
$message.warning(res.message)
}
} catch (error) {
$message.error(error.message)
console.error(error)
$message.removeMessage()
}
loging.value = false
}