-
Notifications
You must be signed in to change notification settings - Fork 1
/
errors.go
85 lines (67 loc) · 2.2 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
package mid
import (
"context"
"net/http"
"github.com/AhmedShaef/wakt/business/sys/validate"
v1Web "github.com/AhmedShaef/wakt/business/web/v1"
"github.com/AhmedShaef/wakt/foundation/web"
"go.uber.org/zap"
)
// Errors handles errors coming out of the call chain. It detects normal
// application errors which are used to respond to the client in a uniform way.
// Unexpected errors (status >= 500) are logged.
func Errors(log *zap.SugaredLogger) web.Middleware {
// This is the actual middleware function to be executed.
m := func(handler web.Handler) web.Handler {
// Create the handler that will be attached in the middleware chain.
h := func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// If the context is missing this value, request the service
// to be shutdown gracefully.
v, err := web.GetValues(ctx)
if err != nil {
return web.NewShutdownError("web value missing from context")
}
// Run the next handler and catch any propagated error.
if err := handler(ctx, w, r); err != nil {
// Log the error.
log.Errorw("ERROR", "traceID", v.TraceID, "message", err)
// Build out the error response.
var er v1Web.ErrorResponse
var status int
switch {
case validate.IsFieldErrors(err):
fieldErrors := validate.GetFieldErrors(err)
er = v1Web.ErrorResponse{
Error: "data validation error",
Fields: fieldErrors.Fields(),
}
status = http.StatusBadRequest
case v1Web.IsRequestError(err):
reqErr := v1Web.GetRequestError(err)
er = v1Web.ErrorResponse{
Error: reqErr.Error(),
}
status = reqErr.Status
default:
er = v1Web.ErrorResponse{
Error: http.StatusText(http.StatusInternalServerError),
}
status = http.StatusInternalServerError
}
// Respond with the error back to the client.
if err := web.Respond(ctx, w, er, status); err != nil {
return err
}
// If we receive the shutdown err we need to return it
// back to the base handler to shut down the service.
if ok := web.IsShutdown(err); ok {
return err
}
}
// The error has been handled, so we can stop propagating it.
return nil
}
return h
}
return m
}