内网服务访问外部第三方 API 的统一网关
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

79 lines
1.5 KiB

package utils
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
type BusinessError struct {
Code int
Msg string
}
type ErrorResult struct {
Msg string `json:"msg,omitempty"`
}
func (e *BusinessError) Error() string {
return e.Msg
}
func NewBusinessError(code int, msg string) *BusinessError {
return &BusinessError{code, msg}
}
func ErrorHandler(c *gin.Context) {
c.Next()
for _, e := range c.Errors {
switch err := e.Err.(type) {
case *BusinessError:
GinLogger(c).ERROR(err.Msg, "err", err.Error())
c.JSON(err.Code, &ErrorResult{err.Msg})
default:
GinLogger(c).ERROR("generic error", "err", err.Error())
c.JSON(http.StatusInternalServerError, "ERROR")
}
return
}
}
func ThrowAgError(c *gin.Context, err *BusinessError) {
c.AbortWithError(err.Code, err)
}
func Error(c *gin.Context, code int, msg string) {
c.AbortWithError(code, &BusinessError{code, msg})
}
func AuthError(c *gin.Context) {
Error(c, http.StatusUnauthorized, "INVALID_TOKEN")
}
func CodeError(c *gin.Context) {
Error(c, http.StatusBadRequest, "WRONG_CODE")
}
func ParamError(c *gin.Context) {
Error(c, http.StatusBadRequest, "INVALID_PARAM")
}
func PermissionError(c *gin.Context) {
Error(c, http.StatusForbidden, "NO_PERMISSION")
}
func DbError(c *gin.Context) {
Error(c, http.StatusInternalServerError, "DB_ERROR")
}
// 错误日志就近输出,后续不需要重复输出
// 无错误返回true
func ErrorCheckAndLog(err error) bool {
if err != nil {
log.Println("db:", err)
return false
}
return true
}