From 06d5fe51e59e0a22de4665b63f7ae76797816e50 Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Tue, 18 May 2021 10:19:10 +0200 Subject: [PATCH] feat: add optional error data --- api/error.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/api/error.go b/api/error.go index 36d8800..afb4d13 100644 --- a/api/error.go +++ b/api/error.go @@ -1,6 +1,7 @@ package api import ( + "encoding/json" "fmt" ) @@ -14,8 +15,31 @@ type Err struct { Reason string `json:"reason"` // associated HTTP status Status int + // data that can be added to document the error + data []interface{} `json:"data"` } func (e Err) Error() string { return fmt.Sprintf("[%d] %s", e.Code, e.Reason) } + +// With adds data to document the error and returns the updated error +func (e Err) With(data ...interface{}) Err { + if e.data == nil { + e.data = make([]interface{}, 0) + } + e.data = append(e.data, data...) + return e +} + +// MarshalJSON implements the 'json.Marshaler' interface and is used +// to generate the JSON representation of the error +func (e Err) MarshalJSON() ([]byte, error) { + fmt := make(map[string]interface{}) + fmt["code"] = e.Code + fmt["reason"] = e.Reason + if len(e.data) > 0 { + fmt["data"] = e.data + } + return json.Marshal(fmt) +} -- 2.40.1