/
errors.go
84 lines (74 loc) · 2.7 KB
/
errors.go
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package server
import (
"errors"
"fmt"
"net/http"
"github.com/lazygo/lazygo/utils"
)
// Errors
var (
ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType)
ErrNotFound = NewHTTPError(http.StatusNotFound)
ErrUnauthorized = NewHTTPError(http.StatusUnauthorized)
ErrForbidden = NewHTTPError(http.StatusForbidden)
ErrMethodNotAllowed = NewHTTPError(http.StatusMethodNotAllowed)
ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge)
ErrTooManyRequests = NewHTTPError(http.StatusTooManyRequests)
ErrBadRequest = NewHTTPError(http.StatusBadRequest)
ErrBadGateway = NewHTTPError(http.StatusBadGateway)
ErrInternalServerError = NewHTTPError(http.StatusInternalServerError)
ErrRequestTimeout = NewHTTPError(http.StatusRequestTimeout)
ErrServiceUnavailable = NewHTTPError(http.StatusServiceUnavailable)
ErrValidatorNotRegistered = errors.New("validator not registered")
ErrActionNotExists = errors.New("action not exists")
ErrInvalidRedirectCode = errors.New("invalid redirect status code")
ErrCookieNotFound = errors.New("cookie not found")
ErrInvalidListenerNetwork = errors.New("invalid listener network")
)
// Error handlers
var (
NotFoundHandler = func(c Context) error {
return ErrNotFound
}
MethodNotAllowedHandler = func(c Context) error {
return ErrMethodNotAllowed
}
)
// HTTPError represents an error that occurred while handling a request.
type HTTPError struct {
Code int `json:"code"`
Errno int `json:"errno"`
Message any `json:"message"`
Internal error `json:"-"` // Stores the error returned by an external dependency
}
// NewHTTPError creates a new HTTPError instance.
func NewHTTPError(code int, message ...any) *HTTPError {
he := &HTTPError{Code: code, Errno: code, Message: http.StatusText(code)}
switch len(message) {
case 0:
case 1:
he.Message = message[0]
case 2:
he.Errno = utils.ToInt(message[0], -1)
he.Message = message[1]
default:
he.Message = message[0]
}
return he
}
// Error makes it compatible with `error` interface.
func (he *HTTPError) Error() string {
if he.Internal == nil {
return fmt.Sprintf("code=%d, errno=%d, message=%v", he.Code, he.Errno, he.Message)
}
return fmt.Sprintf("code=%d, errno=%d, message=%v, internal=%v", he.Code, he.Errno, he.Message, he.Internal)
}
// SetInternal sets error to HTTPError.Internal
func (he *HTTPError) SetInternal(err error) *HTTPError {
he.Internal = err
return he
}
// Unwrap satisfies the Go 1.13 error wrapper interface.
func (he *HTTPError) Unwrap() error {
return he.Internal
}