Przeglądaj źródła

错误码比较

jys 2 lat temu
rodzic
commit
3dcc1f0b7a
3 zmienionych plików z 12 dodań i 5 usunięć
  1. 3 4
      v2alpha/code.go
  2. 1 1
      v2alpha/errors.go
  3. 8 0
      v2alpha/public.go

+ 3 - 4
v2alpha/code.go

@@ -1,7 +1,6 @@
 package fserr
 
 import (
-	"fmt"
 	"net/http"
 )
 
@@ -28,7 +27,7 @@ type ErrCode struct {
 	HttpCode int `json:"httpCode,omitempty"`
 	// BusinessCode 该错误码对应的业务码
 	// +optional
-	BusinessCode string `json:"businessCode,omitempty"`
+	BusinessCode int `json:"businessCode,omitempty"`
 	// Message 该错误码对应的错误信息
 	// +optional
 	Message string `json:"message,omitempty"`
@@ -38,12 +37,12 @@ type ErrCode struct {
 // 当错误码匹配失败时,提供的备选方案,已内置默认错误码,
 // 它的HTTP码为200,业务码和信息均为零值
 func SetDefault(httpCode, businessCode int, message string) {
-	defaultErrCode = ErrCode{httpCode, fmt.Sprintf("%06d", serviceCode+businessCode), message}
+	defaultErrCode = ErrCode{httpCode, serviceCode + businessCode, message}
 }
 
 // NewCode 创建指定信息的错误码
 func NewCode(httpCode, businessCode int, message string) ErrCode {
-	code := ErrCode{httpCode, fmt.Sprintf("%06d", serviceCode+businessCode), message}
+	code := ErrCode{httpCode, serviceCode + businessCode, message}
 	register(businessCode, code)
 	return code
 }

+ 1 - 1
v2alpha/errors.go

@@ -79,7 +79,7 @@ type withCode struct {
 	cause        error
 	Msg          string `json:"msg"`
 	HttpCode     int    `json:"httpCode"`
-	BusinessCode string `json:"businessCode"`
+	BusinessCode int    `json:"businessCode"`
 }
 
 func (w *withCode) Error() string { return w.Msg }

+ 8 - 0
v2alpha/public.go

@@ -99,6 +99,14 @@ func ParseCode(err error) *withCode {
 	}
 }
 
+func IsCode(err error, code int) bool {
+	var target *withCode
+	if !As(err, &target) {
+		return false
+	}
+	return target.BusinessCode == code
+}
+
 // SetServiceCode 设置服务错误码
 func SetServiceCode(code int) {
 	serviceCode = code