File size: 921 Bytes
ca7217f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | package errors
import (
"encoding/json"
"fmt"
"net/http"
)
// HTTPError implements error interface with HTTP status code.
type HTTPError struct {
Code int `json:"code"`
Message string `json:"message"`
}
// Error implements the error interface and returns a string.
func (e *HTTPError) Error() string {
if e.Message != "" {
return e.Message
}
if text := http.StatusText(e.Code); text != "" {
return text
}
return fmt.Sprintf("error code: %d", e.Code)
}
func (e *HTTPError) StatusCode() int {
return e.Code
}
func (e *HTTPError) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any{
"code": e.Code,
"message": e.Error(),
})
}
func New(code int, message string) error {
return &HTTPError{
Code: code,
Message: message,
}
}
func FromCode(code int) error {
return &HTTPError{
Code: code,
Message: http.StatusText(code),
}
}
var _ error = (*HTTPError)(nil)
|