123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- package rest
- import (
- "net/http"
- )
- var (
- Err = Error{}
- ErrMovedPermanently = NewError(http.StatusMovedPermanently, "")
- ErrFound = NewError(http.StatusFound, "")
- ErrTemporaryRedirect = NewError(http.StatusTemporaryRedirect, "")
- ErrPermanentRedirect = NewError(http.StatusPermanentRedirect, "")
- ErrBadRequest = NewError(http.StatusBadRequest, "")
- ErrUnauthorized = NewError(http.StatusUnauthorized, "")
- ErrPaymentRequired = NewError(http.StatusPaymentRequired, "")
- ErrForbidden = NewError(http.StatusForbidden, "")
- ErrNotFound = NewError(http.StatusNotFound, "")
- ErrMethodNotAllowed = NewError(http.StatusMethodNotAllowed, "")
- ErrNotAcceptable = NewError(http.StatusNotAcceptable, "")
- ErrInternalServerError = NewError(http.StatusInternalServerError, "")
- ErrNotImplemented = NewError(http.StatusNotImplemented, "")
- ErrBadGateway = NewError(http.StatusBadGateway, "")
- ErrServiceUnavailable = NewError(http.StatusServiceUnavailable, "")
- ErrGatewayTimeout = NewError(http.StatusGatewayTimeout, "")
- )
- type Error struct {
- StatusCode int `json:"-"`
- Message string `json:"message"`
- Data map[string]interface{} `json:"data,omitempty"`
- }
- func (e Error) Error() string {
- return e.Message
- }
- func (e Error) Is(target error) bool {
- if t, ok := target.(Error); ok {
- return t.StatusCode == e.StatusCode || t.StatusCode == 0
- }
- return false
- }
- func (e Error) WithData(data map[string]interface{}) Error {
- if e.Data == nil {
- e.Data = map[string]any{}
- }
- for key, value := range data {
- e.Data[key] = value
- }
- return e
- }
- func (e Error) WithError(err error) Error {
- if e.Message == "" {
- return e.WithMessage(err.Error())
- }
- return e.WithData(map[string]interface{}{
- "error": err.Error(),
- })
- }
- func (e Error) WithMessage(message string) Error {
- e.Message = message
- return e
- }
- func (e Error) WithValue(name string, value any) Error {
- return e.WithData(map[string]any{
- name: value,
- })
- }
- func (e Error) Write(w http.ResponseWriter) (int, error) {
- if e.StatusCode == 0 {
- e.StatusCode = 200
- }
- w.WriteHeader(e.StatusCode)
- return w.Write([]byte(e.Message))
- }
- func (e Error) WriteJSON(w http.ResponseWriter) error {
- if e.StatusCode == 0 {
- e.StatusCode = 200
- }
- return WriteResponseJSON(w, e.StatusCode, e)
- }
- func NewError(statusCode int, message string) Error {
- if len(message) == 0 {
- message = http.StatusText(statusCode)
- }
- return Error{
- StatusCode: statusCode,
- Message: message,
- }
- }
|