69 lines
1.7 KiB
Go
69 lines
1.7 KiB
Go
package middleware
|
|
|
|
import (
|
|
"likedream-goframe/internal/ent"
|
|
"likedream-goframe/internal/framework/errors"
|
|
"likedream-goframe/internal/utils"
|
|
|
|
"github.com/gogf/gf/v2/errors/gcode"
|
|
"github.com/gogf/gf/v2/errors/gerror"
|
|
"github.com/gogf/gf/v2/net/ghttp"
|
|
"github.com/gogf/gf/v2/util/gvalid"
|
|
)
|
|
|
|
func ExceptionHandler(r *ghttp.Request) {
|
|
r.Middleware.Next()
|
|
|
|
// 404直接返回
|
|
if r.Response.Status == 404 {
|
|
return
|
|
}
|
|
if r.Response.BufferLength() > 0 {
|
|
return
|
|
}
|
|
if r.Response.Header().Get("Content-Type") == "image/png" {
|
|
return
|
|
}
|
|
var (
|
|
err = r.GetError()
|
|
res = r.GetHandlerResponse()
|
|
code = gerror.Code(err)
|
|
)
|
|
|
|
// 如果没有异常,则直接返回
|
|
if err == nil && res != nil {
|
|
r.Response.ClearBuffer()
|
|
if _, ok := (res).(utils.IResponse); ok {
|
|
r.Response.WriteJson(res)
|
|
} else {
|
|
r.Response.WriteJson(utils.SuccessWithData(res))
|
|
}
|
|
return
|
|
}
|
|
// 如果是参数校验异常
|
|
if ent.IsValidationError(err) {
|
|
tmpErr := errors.CodeParam
|
|
code = tmpErr.Code()
|
|
// 如果是参数唯一值异常
|
|
} else if ent.IsConstraintError(err) {
|
|
tmpErr := errors.CodeParam
|
|
tmpErr.SetMessage((err.(*ent.ConstraintError)).Error())
|
|
code = tmpErr.Code()
|
|
} else if code == gcode.CodeNil {
|
|
code = errors.CodeInternal.Code()
|
|
} else if code == gcode.CodeValidationFailed {
|
|
// 请求参数校验失败返回第一个错误信息
|
|
if validationErr, ok := err.(gvalid.Error); ok {
|
|
if firstErr := validationErr.FirstError(); firstErr != nil {
|
|
c := errors.CodeParam
|
|
c.SetMessage(firstErr.Error())
|
|
code = c.Code()
|
|
}
|
|
}
|
|
}
|
|
r.Response.ClearBuffer()
|
|
r.Response.WriteHeader(200)
|
|
r.Response.WriteJson(utils.Success(code.Code(), code.Message(), code.Detail()))
|
|
|
|
}
|