-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror.go
113 lines (90 loc) · 2.44 KB
/
error.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package rest
import (
"errors"
"net/http"
"github.com/labstack/echo/v4"
)
// HTTPCodeAsError exposes HTTP status code as use case error that can be translated to response status.
type HTTPCodeAsError int
// Error return HTTP status text.
func (c HTTPCodeAsError) Error() string {
return http.StatusText(int(c))
}
// HTTPStatus returns HTTP status code.
func (c HTTPCodeAsError) HTTPStatus() int {
return int(c)
}
// ErrWithHTTPStatus exposes HTTP status code.
type ErrWithHTTPStatus interface {
error
HTTPStatus() int
}
// ErrWithFields exposes structured context of error.
type ErrWithFields interface {
error
Fields() map[string]interface{}
}
// ErrWithAppCode exposes application error code.
type ErrWithAppCode interface {
error
AppErrCode() int
}
// Err creates HTTP status code and ErrResponse for error.
func Err(err error) (int, ErrResponse) {
if err == nil {
panic("nil error received")
}
er := ErrResponse{}
var (
withHTTPStatus ErrWithHTTPStatus
withAppCode ErrWithAppCode
withFields ErrWithFields
)
er.err = err
er.ErrorText = err.Error()
er.httpStatusCode = http.StatusInternalServerError
if he, ok := err.(*echo.HTTPError); ok {
if he.Internal != nil {
if herr, ok := he.Internal.(*echo.HTTPError); ok {
he = herr
}
}
er.httpStatusCode = he.Code
if m, ok := he.Message.(string); ok {
er.ErrorText = m
}
}
if errors.As(err, &withHTTPStatus) {
er.httpStatusCode = withHTTPStatus.HTTPStatus()
}
if errors.As(err, &withAppCode) {
er.AppCode = withAppCode.AppErrCode()
}
if errors.As(err, &withFields) {
er.Context = withFields.Fields()
}
if er.ErrorText == er.StatusText {
er.ErrorText = ""
}
return er.httpStatusCode, er
}
// ErrResponse is HTTP error response body.
type ErrResponse struct {
StatusText string `json:"status,omitempty" description:"Status text."`
AppCode int `json:"code,omitempty" description:"Application-specific error code."`
ErrorText string `json:"error,omitempty" description:"Error message."`
Context map[string]interface{} `json:"context,omitempty" description:"Application context."`
err error // Original error.
httpStatusCode int // HTTP response status code.
}
// Error implements error.
func (e ErrResponse) Error() string {
if e.ErrorText != "" {
return e.ErrorText
}
return e.StatusText
}
// Unwrap returns parent error.
func (e ErrResponse) Unwrap() error {
return e.err
}