|
@@ -0,0 +1,89 @@
|
|
|
+package rest
|
|
|
+
|
|
|
+import (
|
|
|
+ "net/http"
|
|
|
+)
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+type Error struct {
|
|
|
+ StatusCode int `json:"statusCode"`
|
|
|
+ Message string `json:"message"`
|
|
|
+ Data map[string]interface{} `json:"data,omitempty"`
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+func (e Error) Error() string {
|
|
|
+ if e.Data != nil && e.Data["error"] != nil {
|
|
|
+ if value, ok := e.Data["error"].(string); ok {
|
|
|
+ return value
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return e.Message
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+func (e Error) Is(target error) bool {
|
|
|
+ t, ok := target.(Error)
|
|
|
+ if !ok {
|
|
|
+ return false
|
|
|
+ }
|
|
|
+ if t.StatusCode == 0 {
|
|
|
+ return true
|
|
|
+ }
|
|
|
+ return t.StatusCode == e.StatusCode
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+func (e Error) WithData(data map[string]interface{}) Error {
|
|
|
+ if e.Data == nil {
|
|
|
+ e.Data = map[string]any{}
|
|
|
+ }
|
|
|
+ if data != nil {
|
|
|
+ for key, value := range data {
|
|
|
+ e.Data[key] = value
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return e
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+func (e Error) WithError(err error) Error {
|
|
|
+ return e.WithData(map[string]interface{}{
|
|
|
+ "error": err.Error(),
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+func (e Error) WithMessage(message string) Error {
|
|
|
+ e.Message = message
|
|
|
+ return e
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+func (e Error) WithValue(name string, value any) Error {
|
|
|
+ return e.WithData(map[string]any{
|
|
|
+ name: value,
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+func (e Error) Write(w http.ResponseWriter) {
|
|
|
+ w.WriteHeader(e.StatusCode)
|
|
|
+ w.Write([]byte(e.Message))
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+func (e Error) WriteJSON(w http.ResponseWriter) error {
|
|
|
+ return WriteResponseJSON(w, e.StatusCode, e)
|
|
|
+}
|