github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/framework/berror/code.go (about) 1 // the package is exported from github.com/beego/beego/v2/core/berror 2 3 // Copyright 2023. All Rights Reserved. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 package berror 18 19 import ( 20 "fmt" 21 "sync" 22 ) 23 24 // A Code is an unsigned 32-bit error code as defined in the beego spec. 25 type Code interface { 26 Code() uint32 27 Module() string 28 Desc() string 29 Name() string 30 } 31 32 var defaultCodeRegistry = &codeRegistry{ 33 codes: make(map[uint32]*codeDefinition, 127), 34 } 35 36 // DefineCode defining a new Code 37 // Before defining a new code, please read Beego specification. 38 // desc could be markdown doc 39 func DefineCode(code uint32, module string, name string, desc string) Code { 40 res := &codeDefinition{ 41 code: code, 42 name: name, 43 module: module, 44 desc: desc, 45 } 46 defaultCodeRegistry.lock.Lock() 47 defer defaultCodeRegistry.lock.Unlock() 48 49 if _, ok := defaultCodeRegistry.codes[code]; ok { 50 panic(fmt.Sprintf("duplicate code, code %d has been registered", code)) 51 } 52 defaultCodeRegistry.codes[code] = res 53 return res 54 } 55 56 type codeRegistry struct { 57 lock sync.RWMutex 58 codes map[uint32]*codeDefinition 59 } 60 61 func (cr *codeRegistry) Get(code uint32) (Code, bool) { 62 cr.lock.RLock() 63 defer cr.lock.RUnlock() 64 c, ok := cr.codes[code] 65 return c, ok 66 } 67 68 type codeDefinition struct { 69 code uint32 70 module string 71 desc string 72 name string 73 } 74 75 func (c *codeDefinition) Name() string { 76 return c.name 77 } 78 79 func (c *codeDefinition) Code() uint32 { 80 return c.code 81 } 82 83 func (c *codeDefinition) Module() string { 84 return c.module 85 } 86 87 func (c *codeDefinition) Desc() string { 88 return c.desc 89 }