|
@@ -39,7 +39,7 @@ func Wrap(err error, format string, args ...any) error {
|
|
|
// WithCode 创建带有错误码的error,支持格式化占位符
|
|
|
// 使用option可以替换其中信息
|
|
|
func WithCode[T codeType](err error, businessCode T, options ...Option) error {
|
|
|
- code := getCode(serviceCode + int(businessCode))
|
|
|
+ code := getCode(serviceCode.Load() + int(businessCode))
|
|
|
ret := &withCode{
|
|
|
cause: wrapStack(err),
|
|
|
Msg: code.Message,
|
|
@@ -101,20 +101,20 @@ func As(err error, target any) bool { return errors.As(err, target) }
|
|
|
// 若想得到原始的错误码错误,可以使用As方法
|
|
|
func ParseCode(err error) *withCode {
|
|
|
var target *withCode
|
|
|
- if !As(err, &target) {
|
|
|
+ if As(err, &target) {
|
|
|
return &withCode{
|
|
|
- cause: nil,
|
|
|
- Msg: err.Error(),
|
|
|
- HttpCode: defaultErrCode.HttpCode,
|
|
|
- BusinessCode: serviceCode,
|
|
|
+ cause: target.cause,
|
|
|
+ Msg: outerMsg(err),
|
|
|
+ HttpCode: target.HttpCode,
|
|
|
+ BusinessCode: target.BusinessCode,
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return &withCode{
|
|
|
- cause: target.cause,
|
|
|
- Msg: outerMsg(err),
|
|
|
- HttpCode: target.HttpCode,
|
|
|
- BusinessCode: target.BusinessCode,
|
|
|
+ cause: nil,
|
|
|
+ Msg: err.Error(),
|
|
|
+ HttpCode: defaultErrCode.HttpCode,
|
|
|
+ BusinessCode: serviceCode.Load(),
|
|
|
}
|
|
|
}
|
|
|
|
|
@@ -124,14 +124,14 @@ func IsCode[T codeType](err error, code T) bool {
|
|
|
if !As(err, &target) {
|
|
|
return false
|
|
|
}
|
|
|
- return target.BusinessCode == serviceCode+int(code)
|
|
|
+ return target.BusinessCode == serviceCode.Load()+int(code)
|
|
|
}
|
|
|
|
|
|
// SetAppCode 设置服务错误码
|
|
|
// 模块码、模块错误码一共四位,指定应用码将拼接在前
|
|
|
// 例如应用码位101,模块码为1,模块错误码为21,那么最终业务错误码为:1010121
|
|
|
func SetAppCode[T codeType](code T) {
|
|
|
- serviceCode = int(code) * 10000
|
|
|
+ serviceCode.Store(int64(code) * 10000)
|
|
|
}
|
|
|
|
|
|
// outerMsg 获取最外层的错误信息
|
|
@@ -152,21 +152,13 @@ func outerMsg(err error) string {
|
|
|
}
|
|
|
|
|
|
func wrapStack(err error) error {
|
|
|
- if _, ok := err.(*fundamental); ok {
|
|
|
- return err
|
|
|
- }
|
|
|
- if _, ok := err.(*withCode); ok {
|
|
|
- return err
|
|
|
- }
|
|
|
- if _, ok := err.(*withMessage); ok {
|
|
|
- return err
|
|
|
- }
|
|
|
- if _, ok := err.(*withStack); ok {
|
|
|
+ switch err.(type) {
|
|
|
+ case *fundamental, *withCode, *withMessage, *withStack:
|
|
|
return err
|
|
|
- }
|
|
|
-
|
|
|
- return &withStack{
|
|
|
- error: err,
|
|
|
- stack: callers(),
|
|
|
+ default:
|
|
|
+ return &withStack{
|
|
|
+ error: err,
|
|
|
+ stack: callers(),
|
|
|
+ }
|
|
|
}
|
|
|
}
|