-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patherrors.go
69 lines (58 loc) · 1.58 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
package otto
import (
"fmt"
"strings"
)
// HTTPError a typed error returned by handlers
type HTTPError struct {
Code int
Err error
}
func (e HTTPError) Error() string {
return e.Err.Error()
}
// ErrorHandler defines the interface of a error handler
type ErrorHandler func(int, error, Context) error
// ErrorHandlers holds a list of ErrorHandlers associated
// to status codes. It also holds a default ErrorHandler that
// will kick in if there is no other ErrorHandlers
type ErrorHandlers struct {
DefaultHandler ErrorHandler
Handlers map[int]ErrorHandler
}
// Get will return a ErrorHandler that is associated with
// the provided status code, if none was found the DefaultHandler
// will be returned
func (e ErrorHandlers) Get(code int) ErrorHandler {
if h, ok := e.Handlers[code]; ok {
return h
}
return e.DefaultHandler
}
// Copy creates a copy of the ErrorHandlers struct
func (e ErrorHandlers) Copy() ErrorHandlers {
handlersCopy := make(map[int]ErrorHandler)
for key, value := range e.Handlers {
handlersCopy[key] = value
}
return ErrorHandlers{
DefaultHandler: e.DefaultHandler,
Handlers: handlersCopy,
}
}
// DefaultErrorHandler will return the error as json
func DefaultErrorHandler(code int, err error, ctx Context) error {
ct := ctx.Request().Header.Get(HeaderContentType)
if ct == "" {
ct = ctx.Request().Header.Get(HeaderAccept)
}
if strings.Contains(ct, "json") {
err = ctx.JSON(code, map[string]interface{}{
"error": fmt.Sprintf("%+v", err),
"code": code,
})
} else {
err = ctx.String(code, fmt.Sprintf("%+v", err))
}
return err
}