Add 路由中间件 - 异常捕获

This commit is contained in:
新亮
2019-08-31 21:17:16 +08:00
parent 110d9daf20
commit fd2b24aea6
4 changed files with 37 additions and 3 deletions
+1 -1
View File
@@ -21,7 +21,7 @@
- [ ] AES 对称加密
- [ ] RSA 非对称加密
- [x] 日志记录
- [ ] 异常捕获
- [x] 异常捕获
- [ ] 链路追踪(Jaeger
- [ ] 自定义告警
- [ ] 邮件(gomail
+1 -1
View File
@@ -23,5 +23,5 @@ const (
ErrorNotifyUser = "xinliangnote@163.com"
// 告警开关 1=开通 -1=关闭
ErrorNotifyOpen = 1
ErrorNotifyOpen = -1
)
@@ -0,0 +1,32 @@
package exception
import (
"fmt"
"github.com/gin-gonic/gin"
"go-gin-api/app/config"
"go-gin-api/app/util"
"runtime/debug"
"strings"
"time"
)
func SetUp() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
subject := fmt.Sprintf("[Panic - %s] 项目出错了!", config.AppName)
body := fmt.Sprintf("<b>错误时间:%s\n Runtime\n</b>%s",time.Now().Format("2006/01/02 - 15:04:05"), string(debug.Stack()))
bodyHtml := ""
for _,v := range strings.Split(body, "\n") {
bodyHtml += v + "<br>"
}
_ = util.SendMail(config.ErrorNotifyUser, subject, bodyHtml)
utilGin := util.Gin{Ctx:c}
utilGin.Response(500, "系统异常,请联系管理员!", nil)
}
}()
c.Next()
}
}
+3 -1
View File
@@ -3,13 +3,15 @@ package route
import (
"github.com/gin-gonic/gin"
"go-gin-api/app/controller/product"
"go-gin-api/app/route/middleware/exception"
"go-gin-api/app/route/middleware/logger"
"go-gin-api/app/util"
)
func SetupRouter(engine *gin.Engine) {
engine.Use(logger.SetUp())
//设置路由中间件
engine.Use(logger.SetUp(), exception.SetUp())
//404
engine.NoRoute(func(c *gin.Context) {