yintai2/app/common/middleware/recovery.go

37 lines
911 B
Go

package middleware
import (
"fmt"
"net/http"
"runtime"
"yintai-api/app/common/response"
"github.com/gin-gonic/gin"
"github.com/gogap/errors"
log "github.com/sirupsen/logrus"
)
func Recovery(ctx *gin.Context) {
defer func() {
if err := recover(); err != nil {
var rsp response.BaseResponse
if e, ok := err.(errors.ErrCode); ok {
rsp.Code = int(e.Code())
rsp.Message = e.Error()
ctx.JSON(http.StatusOK, rsp)
log.Errorf("[%s][%s][%s] %v", ctx.Request.Method, ctx.Request.URL.Path, ctx.Request.URL.RawQuery, e)
} else {
var buf [2 << 10]byte
stack := string(buf[:runtime.Stack(buf[:], true)])
log.Errorf("[%s][%s][%s] Internal ERROR:::%v stack:%s", ctx.Request.Method, ctx.Request.URL.Path, ctx.Request.URL.RawQuery, err, stack)
rsp.Code = -1
rsp.Message = fmt.Sprintf("%v", err)
ctx.JSON(http.StatusOK, rsp)
}
ctx.Abort()
}
}()
ctx.Next()
}