From efceb2efd61fd4bd22eea6b675fb9f1c242c3cac Mon Sep 17 00:00:00 2001 From: "Gustavo \"Guz\" L de Mello" Date: Tue, 25 Feb 2025 14:28:07 -0300 Subject: [PATCH] feat(smalltrip): new exceptions package for structurerd error codes --- smalltrip/exceptions/exceptions.go | 42 ++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 smalltrip/exceptions/exceptions.go diff --git a/smalltrip/exceptions/exceptions.go b/smalltrip/exceptions/exceptions.go new file mode 100644 index 0000000..3e79943 --- /dev/null +++ b/smalltrip/exceptions/exceptions.go @@ -0,0 +1,42 @@ +package exceptions + +import ( + "errors" + "fmt" + "net/http" +) + +type Exception struct { + Status int `json:"status"` // HTTP Status Code + Code string `json:"code"` // Application error code + Message string `json:"message"` // User friendly message + Err error `json:"error,omitempty"` // Go error + Severity Severity `json:"severity"` // Exception level +} + +var ( + _ fmt.Stringer = Exception{} + _ error = Exception{} + _ http.Handler = Exception{} +) + +func (e Exception) String() string { + return fmt.Sprintf("%s %3d %s Exception %q", e.Severity, e.Status, e.Code, e.Message) +} + +func (e Exception) Error() string { + return e.String() +} + +func (e Exception) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if e.handler != nil { + e.handler(e, w, r) + } + + handler, ok := r.Context().Value(handlerFuncCtxKey).(HandlerFunc) + if !ok { + e.handler(e, w, r) + } + + handler(e, w, r) +}