Files
likedream/internal/utils/error.go
T
2025-11-06 21:25:28 +08:00

76 lines
1.3 KiB
Go

package utils
import (
"context"
"errors"
errors2 "likedream-goframe/internal/common/errors"
"github.com/gogf/gf/v2/frame/g"
"github.com/joomcode/errorx"
"github.com/samber/oops"
)
func OkOrPanic(err error, transformer ...func(error) error) {
if err != nil {
if len(transformer) > 0 {
err = transformer[0](err)
}
var businessError *errors2.BusinessError
if errors.As(err, &businessError) {
panic(businessError)
}
var oopsError oops.OopsError
if errors.As(err, &oopsError) {
panic(errors2.NewBusinessError(503, oopsError.Error()))
}
panic(errors2.NewBusinessError(503, err.Error()))
}
}
func Catch(f func()) (err error) {
defer func() {
if r := recover(); r != nil {
actualError, isError := errorx.ErrorFromPanic(r)
if isError {
err = actualError
} else {
panic(r)
}
}
}()
f()
return nil
}
func Pass(err *error) {
if r := recover(); r != nil {
e, ok := errorx.ErrorFromPanic(r)
if ok {
*err = oops.Wrap(e)
} else {
panic(r)
}
}
}
func HandleError(f func(error)) {
if r := recover(); r != nil {
e, ok := errorx.ErrorFromPanic(r)
if ok {
f(oops.Wrap(e))
} else {
panic(r)
}
}
}
func LogError(ctx context.Context, message string, err error) {
if err != nil {
g.Log().Errorf(ctx, "%s: %+v", message, err)
}
}