github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/framework/berror/error.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 "strconv" 22 "strings" 23 24 "github.com/pkg/errors" 25 ) 26 27 // code, msg 28 const errFmt = "ERROR-%d, %s" 29 30 // Error returns an error representing c and msg. If c is OK, returns nil. 31 func Error(c Code, msg string) error { 32 return fmt.Errorf(errFmt, c.Code(), msg) 33 } 34 35 // Errorf returns error 36 func Errorf(c Code, format string, a ...interface{}) error { 37 return Error(c, fmt.Sprintf(format, a...)) 38 } 39 40 func Wrap(err error, c Code, msg string) error { 41 if err == nil { 42 return nil 43 } 44 return errors.Wrap(err, fmt.Sprintf(errFmt, c.Code(), msg)) 45 } 46 47 func Wrapf(err error, c Code, format string, a ...interface{}) error { 48 return Wrap(err, c, fmt.Sprintf(format, a...)) 49 } 50 51 // FromError is very simple. It just parse error msg and check whether code has been register 52 // if code not being register, return unknown 53 // if err.Error() is not valid beego error code, return unknown 54 func FromError(err error) (Code, bool) { 55 msg := err.Error() 56 codeSeg := strings.SplitN(msg, ",", 2) 57 if strings.HasPrefix(codeSeg[0], "ERROR-") { 58 codeStr := strings.SplitN(codeSeg[0], "-", 2) 59 if len(codeStr) < 2 { 60 return Unknown, false 61 } 62 codeInt, e := strconv.ParseUint(codeStr[1], 10, 32) 63 if e != nil { 64 return Unknown, false 65 } 66 if code, ok := defaultCodeRegistry.Get(uint32(codeInt)); ok { 67 return code, true 68 } 69 } 70 return Unknown, false 71 }