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 { export default {
getUser: () => request.get('/user'), 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) { } catch (error) {
tableData.value = [] tableData.value = []
pagination.itemCount = 0 pagination.itemCount = 0
$message.error(error.message)
} finally { } finally {
loading.value = false loading.value = false
} }
@ -103,7 +102,11 @@ function handleSearch() {
handleQuery() handleQuery()
} }
async function handleReset() { 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() await nextTick()
pagination.page = 1 pagination.page = 1
handleQuery() handleQuery()

View File

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

View File

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

View File

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

View File

@ -6,3 +6,9 @@ export function toLogin() {
query: { ...router.currentRoute.value.query, redirect: router.currentRoute.value.path }, 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秒后自动清除 * * loading message不会自动清除除非被替换成非loading message非loading message默认2秒后自动清除
*/ */
removeMessage(message, duration = 2000) { removeMessage(message = loadingMessage, duration = 2000) {
setTimeout(() => { setTimeout(() => {
if (message) { if (message) {
message.destroy() message.destroy()

View File

@ -1,4 +1,7 @@
import { useUserStore } from '@/store/modules/user' 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' }] const WITHOUT_TOKEN_API = [{ url: '/auth/login', method: 'POST' }]
@ -11,3 +14,36 @@ export function addBaseParams(params) {
params.userId = useUserStore().userId 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 { getToken } from '@/utils/token'
import { toLogin } from '@/utils/auth' import { toLogin } from '@/utils/auth'
import { isNullOrUndef } from '@/utils/is' import { isWithoutToken, resolveResError } from './helpers'
import { isWithoutToken } from './helpers'
export function reqResolve(config) { export function reqResolve(config) {
// 防止缓存给get请求加上时间戳
if (config.method === 'get') {
config.params = { ...config.params, t: new Date().getTime() }
}
// 处理不需要token的请求 // 处理不需要token的请求
if (isWithoutToken(config)) { if (isWithoutToken(config)) {
return config return config
@ -35,42 +29,18 @@ export function reqReject(error) {
} }
export function repResolve(response) { export function repResolve(response) {
if (response?.data?.code !== 0) { const { noNeedTip } = response.config
$message.error(response?.data?.message || '操作异常') if (response.data?.code !== 0) {
return Promise.reject(response?.data) const { code, message } = resolveResError(response?.data)
!noNeedTip && $message.error(message)
return Promise.reject({ code, message, error: response?.data })
} }
return Promise.resolve(response?.data) return Promise.resolve(response?.data)
} }
export function repReject(error) { export function repReject(error) {
let { code, message } = error.response?.data || {} const { noNeedTip } = error.response?.config || error.config
if (isNullOrUndef(code)) { const { code, message } = resolveResError(error.response?.data)
// 未知错误 !noNeedTip && $message.error(message)
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 || '操作异常')
return Promise.reject({ code, message, error }) 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 if (new Date().getTime() - time <= 1000 * 60 * 30) return
try { try {
const res = await api.refreshToken() const res = await api.refreshToken()
if (res.code === 0) { setToken(res.data.token)
setToken(res.data.token)
}
} catch (error) {} } catch (error) {}
} }

View File

@ -5,5 +5,5 @@ export default {
getPostById: (id) => request.get(`/post/${id}`), getPostById: (id) => request.get(`/post/${id}`),
addPost: (data) => request.post('/post', data), addPost: (data) => request.post('/post', data),
updatePost: (data) => request.put(`/post/${data.id}`, 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) const $table = ref(null)
/** QueryBar筛选参数可选 */ /** QueryBar筛选参数可选 */
const queryItems = ref({ const queryItems = ref({})
title: '',
})
/** 补充参数(可选) */ /** 补充参数(可选) */
const extraParams = ref({}) const extraParams = ref({})

View File

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

View File

@ -81,29 +81,26 @@ async function handleLogin() {
return return
} }
try { try {
$message.loading('正在验证...')
loging.value = true loging.value = true
$message.loading('正在验证...')
const res = await api.login({ name, password: password.toString() }) const res = await api.login({ name, password: password.toString() })
if (res.code === 0) { $message.success('登录成功')
$message.success('登录成功') setToken(res.data.token)
setToken(res.data.token) if (isRemember.value) {
if (isRemember.value) { lStorage.set('loginInfo', { name, password })
lStorage.set('loginInfo', { name, password })
} else {
lStorage.remove('loginInfo')
}
if (query.redirect) {
const path = query.redirect
Reflect.deleteProperty(query, 'redirect')
router.push({ path, query })
} else {
router.push('/')
}
} else { } else {
$message.warning(res.message) lStorage.remove('loginInfo')
}
if (query.redirect) {
const path = query.redirect
Reflect.deleteProperty(query, 'redirect')
router.push({ path, query })
} else {
router.push('/')
} }
} catch (error) { } catch (error) {
$message.error(error.message) console.error(error)
$message.removeMessage()
} }
loging.value = false loging.value = false
} }