| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- // Package apierr provides HTTP-aware errors and a default error handler.
- package apierr
- import (
- "errors"
- "fmt"
- "net/http"
- )
- // Error carries the HTTP status code that should be returned to the client.
- type Error struct {
- Status int
- Msg string
- }
- func (e *Error) Error() string {
- return e.Msg
- }
- // New returns an error with the given HTTP status code.
- func New(status int, msg string) error {
- return &Error{Status: status, Msg: msg}
- }
- // BadRequest returns a 400 error.
- func BadRequest(format string, args ...any) error {
- return New(http.StatusBadRequest, fmt.Sprintf(format, args...))
- }
- // NotFound returns a 404 error.
- func NotFound(kind string, id int64) error {
- return New(http.StatusNotFound, fmt.Sprintf("%s id=%d not found", kind, id))
- }
- // Status resolves the HTTP status code of err.
- func Status(err error) int {
- var e *Error
- if errors.As(err, &e) {
- return e.Status
- }
- return http.StatusBadRequest
- }
|