1 parent
d2a9033695
commit
734d389a7c
5 files changed
+91
-13
No files matched your search
@@ -3,6 +3,7 @@ package failure
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"git.zhangdeman.cn/zhangdeman/ginframework/fault"
|
||||
"git.zhangdeman.cn/zhangdeman/ginframework/logger"
|
||||
@@ -22,6 +23,20 @@ func WrapContext(ctx context.Context, code int, message string, cause error) err
|
||||
if cause == nil || fault.Internal(cause) {
|
||||
return cause
|
||||
}
|
||||
// 原生 GORM 钩子等扩展点可能返回应用已经分类的业务错误。
|
||||
// 只识别数字场景码,不依赖应用错误类型或把原始错误文案当作分类依据。
|
||||
var (
|
||||
numeric interface{ Code() int }
|
||||
flexible interface{ Code() any }
|
||||
)
|
||||
if errors.As(cause, &numeric) {
|
||||
return cause
|
||||
}
|
||||
if errors.As(cause, &flexible) {
|
||||
if _, ok := flexible.Code().(int); ok {
|
||||
return cause
|
||||
}
|
||||
}
|
||||
result := fault.New(code, message, cause)
|
||||
logger.RecordErrorContext(ctx, message, result)
|
||||
return result
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package failure
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"git.zhangdeman.cn/zhangdeman/ginframework/fault"
|
||||
)
|
||||
|
||||
type numericBusinessError struct{}
|
||||
|
||||
func (*numericBusinessError) Error() string { return "private business message" }
|
||||
func (*numericBusinessError) Code() int { return 1001 }
|
||||
|
||||
type flexibleBusinessError struct{ code any }
|
||||
|
||||
func (*flexibleBusinessError) Error() string { return "private business message" }
|
||||
func (e *flexibleBusinessError) Code() any { return e.code }
|
||||
|
||||
func TestClassifiedExtensionErrorsPreserveIdentity(t *testing.T) {
|
||||
for _, cause := range []error{&numericBusinessError{}, &flexibleBusinessError{code: 1002}, fmt.Errorf("callback: %w", &numericBusinessError{}), fmt.Errorf("callback: %w", &flexibleBusinessError{code: 1003})} {
|
||||
if got := Wrap(901106, "read database record failed", cause); got != cause {
|
||||
t.Fatal("classified application error was wrapped")
|
||||
}
|
||||
}
|
||||
for _, cause := range []error{&flexibleBusinessError{code: "1002"}, &flexibleBusinessError{}, errors.New("raw driver failure")} {
|
||||
got := Wrap(901106, "read database record failed", cause)
|
||||
if !fault.Internal(got) || !errors.Is(got, cause) {
|
||||
t.Fatal("unclassified cause lost source classification")
|
||||
}
|
||||
}
|
||||
}
|
||||