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{}
|
|
|
|
}
|
|
|
|
|
2018-10-01 19:21:27 +00:00
|
|
|
// Put adds an argument to the error
|
2018-06-01 07:09:26 +00:00
|
|
|
// to be displayed back to API caller
|
2018-10-01 19:21:27 +00:00
|
|
|
func (e *Error) Put(arg interface{}) {
|
2018-06-01 07:09:26 +00:00
|
|
|
|
|
|
|
/* (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-10-04 15:05:10 +00:00
|
|
|
// MarshalJSON implements the 'json.Marshaler' interface and is used
|
2018-07-08 23:08:04 +00:00
|
|
|
// 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
|
|
|
|
|
|
|
}
|