apierr.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Package apierr provides HTTP-aware errors and a default error handler.
  2. package apierr
  3. import (
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. )
  8. // Error carries the HTTP status code that should be returned to the client.
  9. type Error struct {
  10. Status int
  11. Msg string
  12. }
  13. func (e *Error) Error() string {
  14. return e.Msg
  15. }
  16. // New returns an error with the given HTTP status code.
  17. func New(status int, msg string) error {
  18. return &Error{Status: status, Msg: msg}
  19. }
  20. // BadRequest returns a 400 error.
  21. func BadRequest(format string, args ...any) error {
  22. return New(http.StatusBadRequest, fmt.Sprintf(format, args...))
  23. }
  24. // NotFound returns a 404 error.
  25. func NotFound(kind string, id int64) error {
  26. return New(http.StatusNotFound, fmt.Sprintf("%s id=%d not found", kind, id))
  27. }
  28. // Status resolves the HTTP status code of err. Errors wrapping unrecovered
  29. // failures (database, network, ...) must have no apierr.Error in their
  30. // chain, hence they resolve to 500.
  31. func Status(err error) int {
  32. var e *Error
  33. if errors.As(err, &e) {
  34. return e.Status
  35. }
  36. return http.StatusInternalServerError
  37. }