feat: add recovery middleware and use negative error codes for system errors

- Added a new recovery middleware
- Use the negative error codes.
This commit is contained in:
ideaa 2024-06-21 12:14:06 +08:00
parent b9be165fd2
commit 920268c632
2 changed files with 28 additions and 3 deletions

25
middlewares/recovery.go Normal file
View File

@ -0,0 +1,25 @@
package middlewares
import (
"runtime/debug"
"github.com/wonli/aqi/logger"
"github.com/wonli/aqi/ws"
)
func Recovery() ws.HandlerFunc {
return func(a *ws.Context) {
defer func() {
if err := recover(); err != nil {
// 获取 panic 发生的堆栈跟踪
stack := debug.Stack()
logger.SugarLog.Errorf("Panic happened: %s \n %s\n", err, stack)
a.SendCode(-30, "服务维护中")
a.Abort()
}
}()
a.Next()
}
}

View File

@ -20,14 +20,14 @@ func Dispatcher(c *Client, request string) {
if c.User != nil { if c.User != nil {
isBanned, bandTime := c.User.IsBanned() isBanned, bandTime := c.User.IsBanned()
if isBanned { if isBanned {
c.SendRawMsg(21, "sys.ban", "You have been ban", bandTime) c.SendRawMsg(-11, "sys.ban", "You have been ban", bandTime)
return return
} }
} }
//请求频率限制5毫秒 //请求频率限制5毫秒
if t.Sub(c.LastRequestTime).Microseconds() <= 5 { if t.Sub(c.LastRequestTime).Microseconds() <= 5 {
c.SendRawMsg(23, "sys.requestLimit", "Your requests are too frequent", nil) c.SendRawMsg(-13, "sys.requestLimit", "Your requests are too frequent", nil)
return return
} else { } else {
//更新最后请求时间 //更新最后请求时间
@ -42,7 +42,7 @@ func Dispatcher(c *Client, request string) {
handlers := InitManager().Handlers(action) handlers := InitManager().Handlers(action)
if handlers == nil || len(handlers) == 0 { if handlers == nil || len(handlers) == 0 {
c.SendRawMsg(25, action, "Request not supported", nil) c.SendRawMsg(-15, action, "Request not supported", nil)
return return
} }