2019-05-01 11:44:45 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
2021-05-18 08:19:10 +00:00
|
|
|
"encoding/json"
|
2019-05-01 11:44:45 +00:00
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2021-03-28 16:49:23 +00:00
|
|
|
// Err represents an http response error following the api format.
|
2019-05-02 05:54:45 +00:00
|
|
|
// These are used by the services to set the *execution status*
|
2019-05-01 11:44:45 +00:00
|
|
|
// directly into the response as JSON alongside response output fields.
|
2021-03-28 16:49:23 +00:00
|
|
|
type Err struct {
|
|
|
|
// error code (unique)
|
|
|
|
Code int `json:"code"`
|
|
|
|
// error small description
|
|
|
|
Reason string `json:"reason"`
|
|
|
|
// associated HTTP status
|
|
|
|
Status int
|
2021-05-18 08:19:10 +00:00
|
|
|
// data that can be added to document the error
|
|
|
|
data []interface{} `json:"data"`
|
2020-04-04 14:03:50 +00:00
|
|
|
}
|
|
|
|
|
2021-03-28 16:49:23 +00:00
|
|
|
func (e Err) Error() string {
|
|
|
|
return fmt.Sprintf("[%d] %s", e.Code, e.Reason)
|
2019-05-01 11:44:45 +00:00
|
|
|
}
|
2021-05-18 08:19:10 +00:00
|
|
|
|
|
|
|
// 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)
|
|
|
|
}
|