Skip to content

Commit

Permalink
constants:新增错误码注入方法
Browse files Browse the repository at this point in the history
  • Loading branch information
keepchen committed May 29, 2024
1 parent 0584987 commit 17f1336
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
38 changes: 36 additions & 2 deletions constants/code.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,58 @@ var (

// RegisterCode 注册常量代码
//
// Deprecated: RegisterCode is deprecated,it will be removed in the future.
//
// Please use RegisterCodeTable instead.
//
// i18nMsg key为错误码值,value为错误信息
//
// 与 RegisterCodeSingle 不同的是,此方法是将code表整个覆盖。
//
// 当code码重复时,后者覆盖前者
//
// # 此方法适用于注入【固定】的错误码表的场景
func RegisterCode(language LanguageCode, i18nMsg map[ICodeType]string) {
ctm.mux.Lock()
ctm.maps[language] = i18nMsg
ctm.mux.Unlock()
}

// RegisterCodeTable 注册错误码表
//
// i18nMsg key为错误码值,value为错误信息
//
// 与 RegisterCodeSingle 不同的是,此方法是覆盖对应语言的整个code表。
//
// # 此方法适用于【固定】注入错误码表或需要覆盖默认错误码表的场景
func RegisterCodeTable(language LanguageCode, i18nMsg map[ICodeType]string) {
ctm.mux.Lock()
ctm.maps[language] = i18nMsg
ctm.mux.Unlock()
}

// RegisterCodeSingle 注册单个错误码
//
// 与 RegisterCodeTable 不同的是,此方法更细粒度的注入错误码及对应的错误信息而不是整个覆盖。
//
// 当code码重复时,后者覆盖前者
//
// # 此方法适用于【动态】注入单个错误码的场景
func RegisterCodeSingle(language LanguageCode, code ICodeType, msg string) {
ctm.mux.Lock()
ctm.maps[language][code] = msg
ctm.mux.Unlock()
}

func init() {
once.Do(func() {
ctm = &errorCodeTypeMsgMap{
mux: &sync.RWMutex{},
maps: make(map[LanguageCode]map[ICodeType]string),
}

for language, msg := range initErrorCodeMsgMap {
RegisterCode(language, msg)
for language, codeMsg := range initErrorCodeMsgMap {
RegisterCodeTable(language, codeMsg)
}
})
}
2 changes: 1 addition & 1 deletion http/api/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const (
// 2.空数据序列化结构
func SetupOption(opt Option) {
if opt.ErrNoneCode != nil {
constants.RegisterCode(constants.LanguageEnglish, map[constants.ICodeType]string{opt.ErrNoneCode: opt.ErrNoneCodeMsg})
constants.RegisterCodeSingle(constants.LanguageEnglish, opt.ErrNoneCode, opt.ErrNoneCodeMsg)
anotherErrNoneCode = opt.ErrNoneCode
}
switch opt.EmptyDataStruct {
Expand Down

0 comments on commit 17f1336

Please sign in to comment.