diff --git a/README.md b/README.md index 48c5fad..52c586c 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ - [ ] AES 对称加密 - [ ] RSA 非对称加密 - [x] 日志记录 - - [ ] 异常捕获 + - [x] 异常捕获 - [ ] 链路追踪(Jaeger) - [ ] 自定义告警 - [ ] 邮件(gomail) diff --git a/app/config/config.go b/app/config/config.go index 03040a2..97c0fd4 100644 --- a/app/config/config.go +++ b/app/config/config.go @@ -23,5 +23,5 @@ const ( ErrorNotifyUser = "xinliangnote@163.com" // 告警开关 1=开通 -1=关闭 - ErrorNotifyOpen = 1 + ErrorNotifyOpen = -1 ) diff --git a/app/route/middleware/exception/exception.go b/app/route/middleware/exception/exception.go new file mode 100644 index 0000000..94ebc12 --- /dev/null +++ b/app/route/middleware/exception/exception.go @@ -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("错误时间:%s\n Runtime:\n%s",time.Now().Format("2006/01/02 - 15:04:05"), string(debug.Stack())) + bodyHtml := "" + for _,v := range strings.Split(body, "\n") { + bodyHtml += v + "
" + } + _ = util.SendMail(config.ErrorNotifyUser, subject, bodyHtml) + + utilGin := util.Gin{Ctx:c} + utilGin.Response(500, "系统异常,请联系管理员!", nil) + } + }() + c.Next() + } +} diff --git a/app/route/route.go b/app/route/route.go index 3ca052f..d55fc2b 100644 --- a/app/route/route.go +++ b/app/route/route.go @@ -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) {