-
Notifications
You must be signed in to change notification settings - Fork 14
/
error_handler.go
98 lines (87 loc) · 2.1 KB
/
error_handler.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
package common
import (
"context"
"net/http"
)
const (
missingParam = "Missing one or more of the required parameters"
internalServerError = "Internal Server Error"
unauthorizedError = "Unauthorized error"
downstreamUnavailable = "Downstream system is unavailable"
timeoutDownstream = "Time out from down stream services"
unknownError = "Unknown Error"
)
func HandleError(ctx context.Context, w http.ResponseWriter, kind Kind, message string, cause error, httpErrorMapper func(context.Context, error) *HTTPError) {
err := CreateError(ctx, kind, message, cause)
logEntry := GetLogEntryFromContext(ctx)
logEntry.Error(err)
var fields []KV
if w, ok := cause.(wrappedError); ok {
fields = w.fields
err = CreateError(ctx, kind, message, w.e)
}
httpError := httpErrorMapper(ctx, err)
if httpError == nil {
switch t := cause.(type) {
case CustomError:
httpError = t.HTTPError(ctx)
default:
e := MapError(ctx, err)
httpError = &e
}
}
for _, f := range fields {
httpError.AddField(f.K, f.V)
}
httpError.WriteError(ctx, w)
}
func MapError(ctx context.Context, err error) HTTPError {
var (
httpCode int
errorCode, desc string
)
switch e := err.(type) {
case ErrorKinder:
switch e.(ErrorKinder).ErrorKind() {
case BadRequestError:
httpCode = 400
errorCode = "1001"
desc = missingParam
case InternalError:
httpCode = 500
errorCode = "9998"
desc = internalServerError
case UnauthorizedError:
httpCode = 401
errorCode = "1003"
desc = unauthorizedError
case DownstreamUnavailableError:
httpCode = 503
errorCode = "1013"
desc = downstreamUnavailable
case DownstreamTimeoutError:
httpCode = 504
errorCode = "1005"
desc = timeoutDownstream
default:
httpCode = 500
errorCode = "9999"
desc = unknownError
}
default:
if ctx.Err() == context.DeadlineExceeded {
httpCode = 504
errorCode = "1005"
desc = timeoutDownstream
} else {
httpCode = 500
errorCode = "9999"
desc = unknownError
}
}
return HTTPError{
HTTPCode: httpCode,
Code: errorCode,
Description: desc,
}
}