2018-06-01 07:09:26 +00:00
|
|
|
package err
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2018-07-08 23:08:04 +00:00
|
|
|
// Error represents an http response error following the api format.
|
|
|
|
// These are used by the controllers to set the *execution status*
|
2018-07-08 23:34:21 +00:00
|
|
|
// directly into the response as JSON alongside response output fields.
|
2018-06-01 07:09:26 +00:00
|
|
|
type Error struct {
|
|
|
|
Code int
|
|
|
|
Reason string
|
|
|
|
Arguments []interface{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// BindArgument adds an argument to the error
|
|
|
|
// to be displayed back to API caller
|
|
|
|
func (e *Error) BindArgument(arg interface{}) {
|
|
|
|
|
|
|
|
/* (1) Make slice if not */
|
|
|
|
if e.Arguments == nil {
|
|
|
|
e.Arguments = make([]interface{}, 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
/* (2) Append argument */
|
|
|
|
e.Arguments = append(e.Arguments, arg)
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// Implements 'error'
|
|
|
|
func (e Error) Error() string {
|
|
|
|
|
|
|
|
return fmt.Sprintf("[%d] %s", e.Code, e.Reason)
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2018-07-08 23:08:04 +00:00
|
|
|
// MarshalJSON implements the json.Marshaler interface and is used
|
|
|
|
// to generate the JSON representation of the error data
|
2018-06-01 07:09:26 +00:00
|
|
|
func (e Error) MarshalJSON() ([]byte, error) {
|
|
|
|
|
2018-07-08 23:08:04 +00:00
|
|
|
var jsonArguments string
|
2018-06-01 07:09:26 +00:00
|
|
|
|
|
|
|
/* (1) Marshal 'Arguments' if set */
|
|
|
|
if e.Arguments != nil && len(e.Arguments) > 0 {
|
2018-07-08 23:08:04 +00:00
|
|
|
argRepresentation, err := json.Marshal(e.Arguments)
|
2018-06-01 07:09:26 +00:00
|
|
|
if err == nil {
|
2018-07-08 23:08:04 +00:00
|
|
|
jsonArguments = fmt.Sprintf(",\"arguments\":%s", argRepresentation)
|
2018-06-01 07:09:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
/* (2) Render JSON manually */
|
2018-07-08 23:08:04 +00:00
|
|
|
return []byte(fmt.Sprintf("{\"error\":%d,\"reason\":\"%s\"%s}", e.Code, e.Reason, jsonArguments)), nil
|
2018-06-01 07:09:26 +00:00
|
|
|
|
|
|
|
}
|