github.com/zooyer/miskit@v1.0.71/errors/errors.go (about) 1 package errors 2 3 import ( 4 "context" 5 "fmt" 6 "sync" 7 8 "github.com/zooyer/miskit/metric" 9 ) 10 11 type Error struct { 12 errno int 13 error error 14 message string 15 16 record bool 17 metric bool 18 } 19 20 const ( 21 Success = 0 22 InvalidRequest = 1 23 UnknownError = 3 24 ServicePanic = 4 25 ) 26 27 var mutex sync.Mutex 28 29 var prefix = "miskit" 30 31 var msg = map[int]string{ 32 Success: "ok", 33 InvalidRequest: "请求无效", 34 UnknownError: "未知错误", 35 ServicePanic: "程序崩溃", 36 } 37 38 func (e Error) String() string { 39 if e.error == nil { 40 return fmt.Sprintf("%s errno: %d, message:%s", prefix, e.errno, e.message) 41 } 42 return fmt.Sprintf("%s errno: %d, message:%s, error:%v", prefix, e.errno, e.message, e.error) 43 } 44 45 func (e Error) Errno() int { 46 return e.errno 47 } 48 49 func (e Error) Error() string { 50 return e.String() 51 } 52 53 func (e Error) Unwrap() error { 54 return e.error 55 } 56 57 func (e Error) Metric() { 58 if e.metric { 59 return 60 } 61 e.metric = true 62 63 metric.Count("errors::"+prefix, 1, map[string]interface{}{ 64 "errno": e.errno, 65 "message": e.message, 66 }) 67 } 68 69 func (e Error) Record(ctx context.Context) Error { 70 if e.record { 71 return e 72 } 73 e.record = true 74 // TODO LOG 75 fmt.Println("LOG::errors:", e) 76 return e 77 } 78 79 func Register(name string, errno map[int]string) { 80 mutex.Lock() 81 defer mutex.Unlock() 82 83 prefix = name 84 85 for errno, message := range errno { 86 if _, exists := msg[errno]; exists { 87 panic(fmt.Sprintf("errno: Define called twice for errno %d", errno)) 88 } 89 msg[errno] = message 90 } 91 } 92 93 func New(errno int, error error) Error { 94 if err, ok := error.(Error); ok { 95 return err 96 } 97 98 return Error{ 99 errno: errno, 100 error: error, 101 message: Msg(errno), 102 record: false, 103 metric: false, 104 } 105 } 106 107 func Msg(errno int) string { 108 if msg, exists := msg[errno]; exists { 109 return msg 110 } 111 return "未定义错误码" 112 } 113 114 func Is(err error, errno int) bool { 115 if e, ok := err.(Error); ok { 116 return e.errno == errno 117 } 118 return false 119 }