Sfoglia il codice sorgente

应用码取消2位限制

jys 1 anno fa
parent
commit
7a5423c9dd
2 ha cambiato i file con 12 aggiunte e 23 eliminazioni
  1. 4 15
      public.go
  2. 8 8
      public_test.go

+ 4 - 15
public.go

@@ -3,8 +3,6 @@ package fserr
 import (
 	"errors"
 	"fmt"
-	"strconv"
-	"strings"
 )
 
 // New 创建新的错误,支持格式化占位符
@@ -104,7 +102,7 @@ func ParseCode(err error) *withCode {
 			cause:        nil,
 			Msg:          err.Error(),
 			HttpCode:     defaultErrCode.HttpCode,
-			BusinessCode: serviceCode * 10000,
+			BusinessCode: serviceCode,
 		}
 	}
 
@@ -126,19 +124,10 @@ func IsCode[T codeType](err error, code T) bool {
 }
 
 // SetAppCode 设置服务错误码
-// 例如设置服务码为300000,用户不存在错误码为2001,
-// 那么最终业务错误码为302001
+// 模块码、模块错误码一共四位,指定应用码将拼接在前
+// 例如应用码位101,模块码为1,模块错误码为21,那么最终业务错误码为:1010121
 func SetAppCode[T codeType](code T) {
-	strCode := strconv.Itoa(int(code))
-	if len(strCode) == 1 {
-		strCode = "0" + strCode
-	}
-	c, err := strconv.ParseInt(strCode+strings.Repeat("0", 6-len(strCode)),
-		10, 64)
-	if err != nil {
-		panic(err)
-	}
-	serviceCode = int(c)
+	serviceCode = int(code) * 10000
 }
 
 // outerMsg 获取最外层的错误信息

+ 8 - 8
public_test.go

@@ -121,10 +121,10 @@ func (s *TestPublicSuite) TestIsCode() {
 }
 
 func (s *TestPublicSuite) TestSetServiceCode() {
-	SetAppCode(300000)
+	SetAppCode(3)
 	NewOK(2001, "ok")
 	err := WithCode(nil, 2001)
-	s.Equal(302001, ParseCode(err).BusinessCode)
+	s.Equal(32001, ParseCode(err).BusinessCode)
 }
 
 func (s *TestPublicSuite) TestWithStack() {
@@ -144,24 +144,24 @@ func TestServiceCode(t *testing.T) {
 	assert.Equal(t, 10001, code.BusinessCode)
 	assert.Equal(t, http.StatusInternalServerError, code.HttpCode)
 
-	SetAppCode(10)
+	SetAppCode(2)
 	NewBadRequest(ErrDb, "db error")
 	code = ParseCode(WithCode(nil, ErrDb))
 	assert.Equal(t, "db error", code.Msg)
-	assert.Equal(t, 100002, code.BusinessCode)
+	assert.Equal(t, 20002, code.BusinessCode)
 	assert.Equal(t, http.StatusBadRequest, code.HttpCode)
 
-	SetAppCode(100000)
+	SetAppCode(3)
 	NewInternalError(ErrParam, "param error")
 	code = ParseCode(WithCode(nil, ErrParam))
 	assert.Equal(t, "param error", code.Msg)
-	assert.Equal(t, 100003, code.BusinessCode)
+	assert.Equal(t, 30003, code.BusinessCode)
 	assert.Equal(t, http.StatusInternalServerError, code.HttpCode)
 
-	SetAppCode(1000)
+	SetAppCode(4)
 	NewConflict(ErrRetry, "retry error")
 	code = ParseCode(WithCode(nil, ErrRetry))
-	assert.Equal(t, 100004, code.BusinessCode)
+	assert.Equal(t, 40004, code.BusinessCode)
 	assert.Equal(t, http.StatusConflict, code.HttpCode)
 	assert.Equal(t, "retry error", code.Msg)
 }