package middleware

import (
	"gadmin/utility/serializer"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"runtime/debug"
)

// Recover 异常接管
func Recover(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			//打印错误堆栈信息
			logrus.Errorf("middleware recover: %v \n stack:%v \n", r, string(debug.Stack()))

			msg := errorToString(r)
			//// 生产环境隐藏报错
			//if gin.Mode() == gin.ReleaseMode {
			//	msg = "服务器居然开小差了，请稍后再试吧！"
			//}
			serializer.JSONErrorExit(c, msg)
			c.Abort()
		}
	}()
	c.Next()
}

// recover错误，转string
func errorToString(r interface{}) string {
	switch v := r.(type) {
	case error:
		return v.Error()
	case *logrus.Entry:
		str, err := r.(*logrus.Entry).String()
		if err != nil {
			return "recover错误:" + err.Error()
		}
		return str
	default:
		return r.(string)
	}
}
