http.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package errors
  2. import (
  3. "errors"
  4. "net/http"
  5. )
  6. // HTTPError is an augmented error with a HTTP status code.
  7. type HTTPError struct {
  8. StatusCode int
  9. error
  10. }
  11. // Error implements the error interface.
  12. func (e *HTTPError) Error() string {
  13. return e.error.Error()
  14. }
  15. // NewMethodNotAllowed returns an appropriate error in the case that
  16. // an HTTP client uses an invalid method (i.e. a GET in place of a POST)
  17. // on an API endpoint.
  18. func NewMethodNotAllowed(method string) *HTTPError {
  19. return &HTTPError{http.StatusMethodNotAllowed, errors.New(`Method is not allowed:"` + method + `"`)}
  20. }
  21. // NewBadRequest creates a HttpError with the given error and error code 400.
  22. func NewBadRequest(err error) *HTTPError {
  23. return &HTTPError{http.StatusBadRequest, err}
  24. }
  25. // NewBadRequestString returns a HttpError with the supplied message
  26. // and error code 400.
  27. func NewBadRequestString(s string) *HTTPError {
  28. return NewBadRequest(errors.New(s))
  29. }
  30. // NewBadRequestMissingParameter returns a 400 HttpError as a required
  31. // parameter is missing in the HTTP request.
  32. func NewBadRequestMissingParameter(s string) *HTTPError {
  33. return NewBadRequestString(`Missing parameter "` + s + `"`)
  34. }
  35. // NewBadRequestUnwantedParameter returns a 400 HttpError as a unnecessary
  36. // parameter is present in the HTTP request.
  37. func NewBadRequestUnwantedParameter(s string) *HTTPError {
  38. return NewBadRequestString(`Unwanted parameter "` + s + `"`)
  39. }