This repository has been archived by the owner on Oct 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
86 lines (73 loc) · 1.98 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
85
86
package enlight
import (
"errors"
"fmt"
"github.com/valyala/fasthttp"
)
// Errors
var (
ErrNotFound = NewHTTPError(fasthttp.StatusNotFound)
ErrInvalidRedirectCode = errors.New("invalid redirect status code")
)
// HTTPError represents an error that occured while handling a request.
type HTTPError struct {
Code int `json:"-"`
Message interface{} `json:"message"`
Internal error `json:"-"` // Stores the error returned by an external dependency
}
// NewHTTPError creates a new HTTPError
func NewHTTPError(code int, message ...interface{}) *HTTPError {
he := &HTTPError{
Code: code,
Message: fasthttp.StatusMessage(code),
}
if len(message) > 0 {
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, message=%v", he.Code, he.Message)
}
return fmt.Sprintf("code=%d, message=%v, internal=%v", he.Code, he.Message, he.Internal)
}
// SetInternal sets error to HTTPError.Internal
func (he *HTTPError) SetInternal(err error) *HTTPError {
he.Internal = err
return he
}
// HTTPErrorHandler is a centralized HTTP error handler.
type HTTPErrorHandler func(error, Context)
// DefaultHTTPErrorHandler is the default HTTP error handler. It sends a JSON response
// with status code.
func (e *Enlight) DefaultHTTPErrorHandler(err error, c Context) {
he, ok := err.(*HTTPError)
if ok {
if he.Internal != nil {
if herr, ok := he.Internal.(*HTTPError); ok {
he = herr
}
}
} else {
he = &HTTPError{
Code: fasthttp.StatusInternalServerError,
Message: fasthttp.StatusMessage(fasthttp.StatusInternalServerError),
}
}
code := he.Code
message := he.Message
if m, ok := message.(string); ok {
message = Map{"message": m}
}
if string(c.Request().Method()) == fasthttp.MethodHead {
err = c.NoContent(he.Code)
} else {
err = c.JSON(code, message)
}
if err != nil {
fmt.Println(err)
// TODO: log the error
}
}