瀏覽代碼

错误码泛型支持

jys 2 年之前
父節點
當前提交
873fcb11fd
共有 2 個文件被更改,包括 8 次插入3 次删除
  1. 5 0
      v2alpha/code.go
  2. 3 3
      v2alpha/public.go

+ 5 - 0
v2alpha/code.go

@@ -4,6 +4,11 @@ import (
 	"net/http"
 )
 
+type codeType interface {
+	int8 | int16 | int32 | int64 | int |
+		uint8 | uint16 | uint32 | uint64 | uint
+}
+
 var serviceCode int
 
 const (

+ 3 - 3
v2alpha/public.go

@@ -34,8 +34,8 @@ func Wrap(err error, format string, args ...any) error {
 
 // WithCode 创建带有错误码的error,支持格式化占位符
 // 使用option可以替换其中信息
-func WithCode(err error, businessCode int, options ...Option) error {
-	code := getCode(businessCode)
+func WithCode[T codeType](err error, businessCode T, options ...Option) error {
+	code := getCode(int(businessCode))
 	ret := &withCode{
 		cause:        err,
 		Msg:          code.Message,
@@ -74,7 +74,7 @@ func Is(err, target error) bool {
 }
 
 // As 匹配最外层的与target类型相同的error,将其赋值给target
-func As(err error, target interface{}) bool { return errors.As(err, target) }
+func As(err error, target any) bool { return errors.As(err, target) }
 
 // ParseCode 将错误解析为错误码错误
 // 若err不是错误码错误,则包裹传递错误,其他信息为默认错误码信息