apierr.go 934 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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.
  29. func Status(err error) int {
  30. var e *Error
  31. if errors.As(err, &e) {
  32. return e.Status
  33. }
  34. return http.StatusBadRequest
  35. }