2019-05-01 11:44:45 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
2020-03-28 13:51:49 +00:00
|
|
|
"encoding/json"
|
2019-05-01 11:44:45 +00:00
|
|
|
"fmt"
|
2020-04-04 14:03:50 +00:00
|
|
|
"net/http"
|
2019-05-01 11:44:45 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Error 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.
|
2020-03-28 13:51:49 +00:00
|
|
|
type Error int
|
2019-05-01 11:44:45 +00:00
|
|
|
|
2020-03-28 13:51:49 +00:00
|
|
|
func (e Error) Error() string {
|
|
|
|
reason, ok := errorReasons[e]
|
|
|
|
if !ok {
|
|
|
|
return ErrorUnknown.Error()
|
2019-05-01 16:15:44 +00:00
|
|
|
}
|
2020-03-28 13:51:49 +00:00
|
|
|
return fmt.Sprintf("[%d] %s", e, reason)
|
2019-05-01 11:44:45 +00:00
|
|
|
}
|
|
|
|
|
2020-04-04 14:03:50 +00:00
|
|
|
// Status returns the associated HTTP status code
|
|
|
|
func (e Error) Status() int {
|
|
|
|
status, ok := errorStatus[e]
|
|
|
|
if !ok {
|
|
|
|
return http.StatusOK
|
|
|
|
}
|
|
|
|
return status
|
|
|
|
}
|
|
|
|
|
2020-03-28 13:51:49 +00:00
|
|
|
// MarshalJSON implements encoding/json.Marshaler interface
|
|
|
|
func (e Error) MarshalJSON() ([]byte, error) {
|
|
|
|
// use unknown error if no reason
|
|
|
|
reason, ok := errorReasons[e]
|
|
|
|
if !ok {
|
|
|
|
return ErrorUnknown.MarshalJSON()
|
|
|
|
}
|
|
|
|
|
|
|
|
// format to proper struct
|
|
|
|
formatted := struct {
|
|
|
|
Code int `json:"code"`
|
|
|
|
Reason string `json:"reason"`
|
|
|
|
}{
|
|
|
|
Code: int(e),
|
|
|
|
Reason: reason,
|
2019-05-01 16:23:57 +00:00
|
|
|
}
|
|
|
|
|
2020-03-28 13:51:49 +00:00
|
|
|
return json.Marshal(formatted)
|
2019-05-01 11:44:45 +00:00
|
|
|
}
|