github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/internal/errors/errors.go (about) 1 package errors 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 "net/http" 8 ) 9 10 // ErrShutdown connection is closed. 11 var ( 12 ErrShutdown = errors.New("connection is shut down") 13 ErrUnsupportedCodec = errors.New("unsupported codec") 14 ErrUnvailableService = errors.New("Unvailable Service") 15 ) 16 17 type ( 18 Error struct { 19 Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` 20 Code int32 `protobuf:"varint,2,opt,name=code,proto3" json:"code,omitempty"` 21 Detail string `protobuf:"bytes,3,opt,name=detail,proto3" json:"detail,omitempty"` 22 Status string `protobuf:"bytes,4,opt,name=status,proto3" json:"status,omitempty"` 23 } 24 ) 25 26 func (self *Error) Error() string { 27 return self.Detail 28 } 29 30 // New generates a custom error. 31 func New(id string, code int32, detail string) error { 32 return &Error{ 33 Id: id, 34 Code: code, 35 Detail: detail, 36 Status: http.StatusText(int(code)), 37 } 38 } 39 40 // Parse tries to parse a JSON string into an error. If that 41 // fails, it will set the given string as the error detail. 42 func Parse(err string) *Error { 43 e := new(Error) 44 errr := json.Unmarshal([]byte(err), e) 45 if errr != nil { 46 e.Detail = err 47 } 48 return e 49 } 50 51 // InternalServerError generates a 500 error. 52 func InternalServerError(id, format string, a ...interface{}) error { 53 return &Error{ 54 Id: id, 55 Code: 500, 56 Detail: fmt.Sprintf(format, a...), 57 Status: http.StatusText(500), 58 } 59 } 60 61 func UnsupportedCodec(id string, a ...interface{}) error { 62 return &Error{ 63 Id: id, 64 Code: 500, 65 Detail: fmt.Sprintf("%s unsupported codec %v", id, a), 66 Status: http.StatusText(500), 67 } 68 } 69 70 // Timeout generates a 408 error. 71 func Timeout(id, format string, a ...interface{}) error { 72 return &Error{ 73 Id: id, 74 Code: 408, 75 Detail: fmt.Sprintf(format, a...), 76 Status: http.StatusText(408), 77 } 78 } 79 80 // NotFound generates a 404 error. 81 func NotFound(id, format string, a ...interface{}) error { 82 return &Error{ 83 Id: id, 84 Code: 404, 85 Detail: fmt.Sprintf(format, a...), 86 Status: http.StatusText(404), 87 } 88 }