git.zd.zone/hrpc/hrpc@v0.0.12/uerror/uerror.go (about) 1 package uerror 2 3 import ( 4 "fmt" 5 "runtime" 6 ) 7 8 type Error struct { 9 Code int 10 Msg string 11 Desc string 12 13 // 调用栈 14 st []uintptr 15 } 16 17 func (e Error) Error() string { 18 return fmt.Sprintf("[%d] %s", e.Code, e.Msg) 19 } 20 21 func New(code int, msg string) error { 22 err := &Error{ 23 Code: code, 24 Msg: msg, 25 } 26 err.st = callers() 27 return err 28 } 29 30 func callers() []uintptr { 31 var pcs [32]uintptr 32 n := runtime.Callers(4, pcs[:]) 33 st := pcs[0:n] 34 return st 35 } 36 37 func Code(e error) int { 38 if e == nil { 39 return 0 40 } 41 err, ok := e.(*Error) 42 if !ok { 43 return 0 44 } 45 if err == (*Error)(nil) { 46 return 0 47 } 48 return int(err.Code) 49 } 50 51 func Msg(e error) string { 52 if e == nil { 53 return "success" 54 } 55 err, ok := e.(*Error) 56 if !ok { 57 return e.Error() 58 } 59 if err == (*Error)(nil) { 60 return "success" 61 } 62 return err.Msg 63 } 64 65 func Err(e error) error { 66 return New(500, e.Error()) 67 }