Skip to content

Commit

Permalink
Add 路由中间件 - 异常捕获
Browse files Browse the repository at this point in the history
  • Loading branch information
xinliangnote committed Aug 31, 2019
1 parent 110d9da commit fd2b24a
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
- [ ] AES 对称加密
- [ ] RSA 非对称加密
- [x] 日志记录
- [ ] 异常捕获
- [x] 异常捕获
- [ ] 链路追踪(Jaeger)
- [ ] 自定义告警
- [ ] 邮件(gomail)
Expand Down
2 changes: 1 addition & 1 deletion app/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ const (
ErrorNotifyUser = "xinliangnote@163.com"

// 告警开关 1=开通 -1=关闭
ErrorNotifyOpen = 1
ErrorNotifyOpen = -1
)
32 changes: 32 additions & 0 deletions app/route/middleware/exception/exception.go
Original file line number Diff line number Diff line change
@@ -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()
}
}
4 changes: 3 additions & 1 deletion app/route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit fd2b24a

Please sign in to comment.