feat: add optional error data
continuous-integration/drone/push Build is failing Details
continuous-integration/drone/pr Build is failing Details

This commit is contained in:
xdrm-brackets 2021-05-18 10:19:10 +02:00
parent e3d24ae1ef
commit 06d5fe51e5
No known key found for this signature in database
GPG Key ID: 99F952DD5DE2439E
1 changed files with 24 additions and 0 deletions

View File

@ -1,6 +1,7 @@
package api package api
import ( import (
"encoding/json"
"fmt" "fmt"
) )
@ -14,8 +15,31 @@ type Err struct {
Reason string `json:"reason"` Reason string `json:"reason"`
// associated HTTP status // associated HTTP status
Status int Status int
// data that can be added to document the error
data []interface{} `json:"data"`
} }
func (e Err) Error() string { func (e Err) Error() string {
return fmt.Sprintf("[%d] %s", e.Code, e.Reason) 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)
}