新增全局异常提示

This commit is contained in:
不做码农 2023-09-29 11:07:56 +08:00
parent b4a37d06c1
commit 405a8ce511
7 changed files with 102 additions and 180 deletions

View File

@ -9,7 +9,7 @@ import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission' import usePermissionStore from '@/store/modules/permission'
NProgress.configure({ showSpinner: false }) NProgress.configure({ showSpinner: false })
const whiteList = ['/login', '/auth-redirect', '/bind', '/register', '/socialLogin'] const whiteList = ['/login', '/auth-redirect', '/bind', '/register', '/socialLogin', '/error']
router.beforeEach((to, from, next) => { router.beforeEach((to, from, next) => {
NProgress.start() NProgress.start()

View File

@ -59,6 +59,11 @@ export const constantRoutes = [
component: () => import('@/views/error/401'), component: () => import('@/views/error/401'),
hidden: true hidden: true
}, },
{
path: '/error',
component: () => import('@/views/error/Error'),
hidden: true
},
{ {
path: '', path: '',
component: Layout, component: Layout,

View File

@ -1,5 +1,4 @@
// import signalr from './signalr' import { ElNotification, ElMessageBox } from 'element-plus'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import useSocketStore from '@/store/modules/socket' import useSocketStore from '@/store/modules/socket'
import useUserStore from '@/store/modules/user' import useUserStore from '@/store/modules/user'
import { webNotify } from '@/utils/index' import { webNotify } from '@/utils/index'
@ -38,15 +37,20 @@ export default {
// 接收强退通知 // 接收强退通知
connection.on('forceUser', (data) => { connection.on('forceUser', (data) => {
ElMessageBox.alert(`你的账号已被强退,原因:${data.reason || '无'}`, '提示', { // connection.stop().then(() => {
confirmButtonText: '确定', // console.log('Connection stoped')
callback: () => { // })
// ElMessageBox.alert(`你的账号已被强退,原因:${data.reason || '无'}`, '提示', {
// confirmButtonText: '确定',
// callback: () => {
// }
// })
useSocketStore().setGlobalError({ code: 0, msg: `你的账号已被强退,原因:${data.reason || '无'}` })
useUserStore() useUserStore()
.logOut() .logOut()
.then(() => { .then(() => {
location.href = import.meta.env.VITE_APP_ROUTER_PREFIX + 'index' location.href = import.meta.env.VITE_APP_ROUTER_PREFIX + 'error'
})
}
}) })
}) })
// 接收聊天数据 // 接收聊天数据
@ -70,7 +74,7 @@ export default {
useSocketStore().getOnlineInfo(data) useSocketStore().getOnlineInfo(data)
}) })
connection.on('logOut', () => { connection.on(MsgType.LogOut, () => {
useUserStore() useUserStore()
.logOut() .logOut()
.then(() => { .then(() => {
@ -86,5 +90,6 @@ export default {
} }
const MsgType = { const MsgType = {
M001: 'onlineNum', M001: 'onlineNum',
M002: 'connId' M002: 'connId',
LogOut: 'logOut'
} }

View File

@ -41,7 +41,6 @@ export default {
await this.start() await this.start()
}) })
analysis.onMessage(connection) analysis.onMessage(connection)
// this.receiveMsg(connection)
// 启动 // 启动
// this.start(); // this.start();
}, },
@ -70,7 +69,5 @@ export default {
} }
return false return false
} }
}, }
// 接收消息处理
receiveMsg(connection) {}
} }

View File

@ -2,7 +2,7 @@ import useUserStore from './user'
import signalR from '@/signalr/signalr' import signalR from '@/signalr/signalr'
const useSocketStore = defineStore('socket', { const useSocketStore = defineStore('socket', {
persist: { persist: {
paths: ['chatMessage', 'chatList', 'sessionList', 'newChat', 'noticeIdArr', 'newNotice'] //存储指定key paths: ['chatMessage', 'chatList', 'sessionList', 'newChat', 'noticeIdArr', 'newNotice', 'globalErrorMsg'] //存储指定key
}, },
state: () => ({ state: () => ({
onlineNum: 0, onlineNum: 0,
@ -16,7 +16,9 @@ const useSocketStore = defineStore('socket', {
sessionList: {}, sessionList: {},
newChat: 0, newChat: 0,
newNotice: 0, newNotice: 0,
noticeIdArr: [] noticeIdArr: [],
// 全局错误提醒
globalErrorMsg: {}
}), }),
getters: { getters: {
/** /**
@ -113,6 +115,9 @@ const useSocketStore = defineStore('socket', {
} else if (type == 1) { } else if (type == 1) {
this.newChat = 0 this.newChat = 0
} }
},
setGlobalError(data) {
this.globalErrorMsg = data
} }
} }
}) })

View File

@ -1,159 +0,0 @@
// 官方文档https://docs.microsoft.com/zh-cn/aspnet/core/signalr/javascript-client?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-2.2&tabs=visual-studio
import * as signalR from '@microsoft/signalr'
import { getToken } from '@/utils/auth'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import useSocketStore from '@/store/modules/socket'
import useUserStore from '@/store/modules/user'
import { webNotify } from './index'
export default {
// signalR对象
SR: {},
// 失败连接重试次数
failNum: 4,
init(url) {
var socketUrl = window.location.origin + url
const connection = new signalR.HubConnectionBuilder()
.withUrl(socketUrl, { accessTokenFactory: () => getToken() })
.withAutomaticReconnect() //自动重新连接
.configureLogging(signalR.LogLevel.Warning)
.build()
this.SR = connection
// 断线重连
connection.onclose(async (error) => {
console.error('断开连接了' + error)
console.assert(connection.state === signalR.HubConnectionState.Disconnected)
// 建议用户重新刷新浏览器
await this.start()
})
connection.onreconnected((connectionId) => {
ElMessage({
message: '与服务器通讯已连接成功',
type: 'success',
duration: 2000
})
console.log('断线重新连接成功' + connectionId)
})
connection.onreconnecting(async () => {
console.log('断线重新连接中... ')
await this.start()
})
this.receiveMsg(connection)
// 启动
// this.start();
},
/**
* 调用 this.signalR.start().then(async () => { await this.SR.invoke("method")})
* @returns
*/
async start() {
try {
console.log('signalR-1', this.SR.state)
//使用async和await 或 promise的then 和catch 处理来自服务端的异常
if (this.SR.state === signalR.HubConnectionState.Disconnected) {
await this.SR.start()
}
console.log('signalR-2', this.SR.state)
return true
} catch (error) {
console.error(error)
this.failNum--
// console.log(`失败重试剩余次数${that.failNum}`, error)
if (this.failNum > 0 && this.SR.state.Disconnected) {
setTimeout(async () => {
await this.start()
}, 5000)
}
return false
}
},
// 接收消息处理
receiveMsg(connection) {
connection.on('onlineNum', (data) => {
useSocketStore().setOnlineUsers(data)
})
// 接收欢迎语
connection.on('welcome', (data) => {
ElNotification.info(data)
})
connection.on('connId', (data) => {
// useUserStore().saveConnId(data)
})
// 接收后台手动推送消息
connection.on('receiveNotice', (title, data) => {
ElNotification({
type: 'info',
title: title,
message: data,
dangerouslyUseHTMLString: true,
duration: 0
})
webNotify({ title: title, body: data })
})
// 接收系统通知/公告
connection.on('moreNotice', (data) => {
if (data.code == 200) {
useSocketStore().setNoticeList(data.data)
}
})
// 接收在线用户
// connection.on('onlineUser', (data) => {
// useSocketStore().setOnlineUsers(data)
// })
// 接收封锁通知
connection.on('lockUser', (data) => {
ElMessageBox.alert(`你的账号已被锁定,剩余,${data.time}分,原因:${data.reason || '-'}`, '提示', {
confirmButtonText: '确定',
callback: (action) => {
useUserStore()
.logOut()
.then(() => {
var redirectUrl = window.location.pathname
if (location.pathname.indexOf('/login') != 0) {
location.href = import.meta.env.VITE_APP_ROUTER_PREFIX + 'index?redirect=' + redirectUrl
}
})
}
})
})
// 接收聊天数据
connection.on('receiveChat', (data) => {
const title = `来自${data.userName}的消息通知`
useSocketStore().setChat(data)
if (data.userid != useUserStore().userId) {
ElNotification({
title: title,
message: data.message,
type: 'success',
duration: 3000
})
}
webNotify({ title: title, body: data.message })
})
connection.on('onlineInfo', (data) => {
console.log('onlineInfo', data)
useSocketStore().getOnlineInfo(data)
})
connection.on('logOut', () => {
useUserStore()
.logOut()
.then(() => {
ElMessageBox.alert(`你的账号已在其他设备登录,如果不是你的操作请尽快修改密码`, '提示', {
confirmButtonText: '确定',
callback: () => {
location.href = import.meta.env.VITE_APP_ROUTER_PREFIX + 'index'
}
})
})
})
}
}

69
src/views/error/Error.vue Normal file
View File

@ -0,0 +1,69 @@
<template>
<div class="errPage-container">
<el-row>
<el-col :span="12">
<h1 class="text-jumbo text-ginormous">提示!</h1>
<h3 class="text-danger">{{ msgObj.msg }}</h3>
<!-- <h6>{{ msgObj }}</h6> -->
<div class="list-unstyled">
<router-link to="/"> 回首页 </router-link>
</div>
</el-col>
<el-col :span="12">
<img :src="errGif" width="313" height="428" alt="Girl has dropped her ice cream." />
</el-col>
</el-row>
</div>
</template>
<script setup>
import errImage from '@/assets/401_images/401.gif'
import useSocketStore from '@/store/modules/socket'
let { proxy } = getCurrentInstance()
const socketStore = useSocketStore()
const msgObj = computed(() => {
return socketStore.globalErrorMsg
})
const errGif = ref(errImage + '?' + +new Date())
</script>
<style lang="scss" scoped>
.errPage-container {
width: 800px;
max-width: 100%;
margin: 100px auto;
.pan-back-btn {
background: #008489;
color: #fff;
border: none !important;
}
.pan-gif {
margin: 0 auto;
display: block;
}
.pan-img {
display: block;
margin: 0 auto;
width: 100%;
}
.text-jumbo {
font-size: 60px;
font-weight: 700;
color: #484848;
}
.list-unstyled {
font-size: 14px;
li {
padding-bottom: 5px;
}
a {
color: #008489;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
}
}
</style>