error.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package authority
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. )
  7. type apiCtx map[string]interface{}
  8. // Error implements the api.Error interface and adds context to error messages.
  9. type apiError struct {
  10. err error
  11. code int
  12. context apiCtx
  13. }
  14. // Cause implements the errors.Causer interface and returns the original error.
  15. func (e *apiError) Cause() error {
  16. return e.err
  17. }
  18. // Error returns an error message with additional context.
  19. func (e *apiError) Error() string {
  20. ret := e.err.Error()
  21. /*
  22. if len(e.context) > 0 {
  23. ret += "\n\nContext:"
  24. for k, v := range e.context {
  25. ret += fmt.Sprintf("\n %s: %v", k, v)
  26. }
  27. }
  28. */
  29. return ret
  30. }
  31. // ErrorResponse represents an error in JSON format.
  32. type ErrorResponse struct {
  33. Status int `json:"status"`
  34. Message string `json:"message"`
  35. }
  36. // StatusCode returns an http status code indicating the type and severity of
  37. // the error.
  38. func (e *apiError) StatusCode() int {
  39. if e.code == 0 {
  40. return http.StatusInternalServerError
  41. }
  42. return e.code
  43. }
  44. // MarshalJSON implements json.Marshaller interface for the Error struct.
  45. func (e *apiError) MarshalJSON() ([]byte, error) {
  46. return json.Marshal(&ErrorResponse{Status: e.code, Message: http.StatusText(e.code)})
  47. }
  48. // UnmarshalJSON implements json.Unmarshaler interface for the Error struct.
  49. func (e *apiError) UnmarshalJSON(data []byte) error {
  50. var er ErrorResponse
  51. if err := json.Unmarshal(data, &er); err != nil {
  52. return err
  53. }
  54. e.code = er.Status
  55. e.err = fmt.Errorf(er.Message)
  56. return nil
  57. }