-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathgwerror.go
74 lines (65 loc) · 2.18 KB
/
gwerror.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
package biz
import (
"fmt"
"toktik/logging"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/sirupsen/logrus"
)
// GWError is the error struct for gateway.
type GWError struct {
HTTPStatusCode int
StatusCode uint32
StatusMsg string
Cause *error
Fields *logrus.Fields
}
func (G GWError) Error() string {
return fmt.Sprintf("http status code: %d, status code: %d, status msg: %s, cause: %v", G.HTTPStatusCode, G.StatusCode, G.StatusMsg, G.Cause)
}
// extractFieldsFromRequest extracts important fields from request context for debugging purpose.
func extractFieldsFromRequest(c *app.RequestContext) logrus.Fields {
return logrus.Fields{"request_context_info": map[string]any{
"request_id": c.Request.Header.Get("X-Request-Id"),
"method": c.Method(),
"host": c.Host(),
"uri": c.URI(),
"ip": c.ClientIP(),
"ua": c.UserAgent(),
"query_args": c.QueryArgs(),
"post_args": c.PostArgs(),
"content_type": c.ContentType(),
"body": c.GetRawData(),
"handler": c.HandlerName(),
}}
}
// LaunchError logs the error and returns the error.
func (G GWError) LaunchError(c *app.RequestContext) {
logger := logging.Logger.WithFields(extractFieldsFromRequest(c))
if G.Fields != nil {
logger = logger.WithFields(*G.Fields)
}
if G.Cause != nil {
logger = logger.WithField("cause", *G.Cause)
}
logger.Debugf("launch error: %v", G)
c.JSON(G.HTTPStatusCode, map[string]any{
"status_code": G.StatusCode,
"status_msg": G.StatusMsg,
})
}
// WithCause adds the cause to the error.
func (G GWError) WithCause(err error) GWError {
G.Cause = &err
return G
}
// WithFields adds the fields to the error.
func (G GWError) WithFields(fields *logrus.Fields) GWError {
G.Fields = fields
return G
}
var (
RPCCallError = GWError{HTTPStatusCode: consts.StatusInternalServerError, StatusCode: 500001, StatusMsg: "RPC call error"}
UnAuthorized = GWError{HTTPStatusCode: consts.StatusUnauthorized, StatusCode: 401001, StatusMsg: "Unauthorized"}
InvalidArguments = GWError{HTTPStatusCode: consts.StatusBadRequest, StatusCode: 400002, StatusMsg: "Invalid arguments"}
)