12345678910111213141516171819202122232425262728293031323334353637 |
- package middleware
- import (
- "net/http"
- "ordonnance/logger"
- "runtime/debug"
- "github.com/gin-gonic/gin"
- )
- func Recover(c *gin.Context) {
- defer func() {
- if r := recover(); r != nil {
- //打印错误堆栈信息
- logger.Infof("panic: %v\n", r)
- debug.PrintStack()
- //封装通用json返回
- c.JSON(http.StatusOK, gin.H{
- "code": 201,
- "msg": errorToString(r),
- "data": nil,
- })
- c.Abort()
- }
- }()
- c.Next()
- }
- // recover错误,转string
- func errorToString(r interface{}) string {
- switch v := r.(type) {
- case error:
- return v.Error()
- default:
- return r.(string)
- }
- }
|