package route import ( "git.hilo.cn/hilo-common/mycontext" "git.hilo.cn/hilo-common/resource/config" "github.com/gin-gonic/gin" "hilo-user/myerr" "hilo-user/req" "hilo-user/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.GameError: myContext.Log.Warnf("request user err -> url:%v, method:%v, userId:%v, err :%+v\n", reqUri, method, userId, h.Error()) resp.GameResponseFail(c, h) 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 } }