Browse Source

新增基础服务码

jys 2 years ago
parent
commit
f104507472
2 changed files with 19 additions and 5 deletions
  1. 14 5
      v2alpha/code.go
  2. 5 0
      v2alpha/public.go

+ 14 - 5
v2alpha/code.go

@@ -5,12 +5,21 @@ import (
 	"net/http"
 )
 
+var serviceCode int
+
 const (
-	ErrBasic = iota + 1
-	ErrDb
-	ErrParam
+	errBasic = iota + 1
+	errDb
 )
 
+func ErrBasic() int {
+	return serviceCode + errBasic
+}
+
+func ErrDb() int {
+	return serviceCode + errDb
+}
+
 // ErrCode 产生error所包含的错误码信息
 // 支持http错误码、业务错误码
 // 可通过下方快捷函数快速创建指定http码的错误码
@@ -29,12 +38,12 @@ type ErrCode struct {
 // 当错误码匹配失败时,提供的备选方案,已内置默认错误码,
 // 它的HTTP码为200,业务码和信息均为零值
 func SetDefault(httpCode, businessCode int, message string) {
-	defaultErrCode = ErrCode{httpCode, fmt.Sprintf("%06d", businessCode), message}
+	defaultErrCode = ErrCode{httpCode, fmt.Sprintf("%06d", serviceCode+businessCode), message}
 }
 
 // NewCode 创建指定信息的错误码
 func NewCode(httpCode, businessCode int, message string) ErrCode {
-	code := ErrCode{httpCode, fmt.Sprintf("%06d", businessCode), message}
+	code := ErrCode{httpCode, fmt.Sprintf("%06d", serviceCode+businessCode), message}
 	register(businessCode, code)
 	return code
 }

+ 5 - 0
v2alpha/public.go

@@ -99,6 +99,11 @@ func ParseCode(err error) *withCode {
 	}
 }
 
+// SetServiceCode 设置服务错误码
+func SetServiceCode(code int) {
+	serviceCode = code
+}
+
 // outerMsg 获取最外层的错误信息
 func outerMsg(err error) string {
 	if err == nil {