errorHandle.go 1.91 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
package route

import (
	"git.hilo.cn/hilo-common/mycontext"
	"git.hilo.cn/hilo-common/resource/config"
	"github.com/gin-gonic/gin"
	"hilo-group/myerr"
	"hilo-group/req"
	"hilo-group/resp"
)

/**
 * 主要是解决错误的统一处理
 */

/*
*
错误包装类,统一处理。
*/
type HandlerFunc func(c *gin.Context) (*mycontext.MyContext, error)

// 对错误进行处理,
func wrapper(handler HandlerFunc) func(c *gin.Context) {
	return func(c *gin.Context) {
		var err error
		var myContext *mycontext.MyContext
		myContext, err = handler(c)
		//防止忘记返回myContext, 单myContext为nil的时候,发出恐慌,导致错误覆盖。
		if myContext == nil {
			myContext = mycontext.CreateMyContext(nil)
		}
		c.Set(mycontext.ACTION_RESULt, true)
		if err != nil {
			c.Set(mycontext.ACTION_RESULt, false)
			reqUri := c.Request.RequestURI
			method := c.Request.Method
			userId, _ := req.GetUserId(c)

			switch h := err.(type) {
			case *myerr.BusinessError:
				myContext.Log.Warnf("request err -> url:%v, method:%v, userId:%v, err :%+v\n", reqUri, method, userId, h.GetErr())
				resp.ResponseBusiness(c, h)
			case *myerr.WaringError:
				myContext.Log.Warningf("request err -> url:%v, method:%v, userId:%v, err :%+v\n", reqUri, method, userId, h.GetErr())
				if config.AppIsRelease() {
					resp.ResponseOk(c, nil)
					//ResponseErrWithStringOperation(c, nil, h.GetMsg())
				} else {
					resp.ResponseWaring(c, h)
				}
			case *myerr.SysError:
				myContext.Log.Errorf("request err -> url:%v, method:%v, userId:%v, err :%+v\n", reqUri, method, userId, h.GetErr())
				resp.ResponseSysError(c, h)
			default:
				// 注意这里,如果是原生的error, 可能打印不出来,使用errors.Wrap配合%+v可以打印堆栈信息,建议上游使用
				myContext.Log.Errorf("request err -> url:%v, method:%v, userId:%v, err :%+v\n", reqUri, method, userId, err)
				resp.ResponseErrWithString(c, err.Error())
			}
		}
		return
	}
}