-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy patherrors.go
133 lines (113 loc) · 4 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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
//
//
// Tencent is pleased to support the open source community by making tRPC available.
//
// Copyright (C) 2023 THL A29 Limited, a Tencent company.
// All rights reserved.
//
// If you have downloaded a copy of the tRPC source code from Tencent,
// please note that tRPC source code is licensed under the Apache 2.0 License,
// A copy of the Apache 2.0 License is included in this file.
//
//
package restful
import (
"context"
"net/http"
"github.com/valyala/fasthttp"
trpcpb "trpc.group/trpc/trpc-protocol/pb/go/trpc"
"trpc.group/trpc-go/trpc-go/errs"
"trpc.group/trpc-go/trpc-go/restful/errors"
)
const (
// MarshalErrorContent is the content of http response body indicating error marshaling failure.
MarshalErrorContent = `{"code": 11, "message": "failed to marshal error"}`
)
// ErrorHandler handles tRPC errors.
type ErrorHandler func(context.Context, http.ResponseWriter, *http.Request, error)
// FastHTTPErrorHandler handles tRPC errors when fasthttp is used.
type FastHTTPErrorHandler func(context.Context, *fasthttp.RequestCtx, error)
// WithStatusCode is the error that corresponds to an HTTP status code.
type WithStatusCode struct {
StatusCode int
Err error
}
// Error implements Go error.
func (w *WithStatusCode) Error() string {
return w.Err.Error()
}
// Unwrap returns the wrapped error.
func (w *WithStatusCode) Unwrap() error {
return w.Err
}
// tRPC error code => http status code
var httpStatusMap = map[trpcpb.TrpcRetCode]int{
errs.RetServerDecodeFail: http.StatusBadRequest,
errs.RetServerEncodeFail: http.StatusInternalServerError,
errs.RetServerNoService: http.StatusNotFound,
errs.RetServerNoFunc: http.StatusNotFound,
errs.RetServerTimeout: http.StatusGatewayTimeout,
errs.RetServerOverload: http.StatusTooManyRequests,
errs.RetServerSystemErr: http.StatusInternalServerError,
errs.RetServerAuthFail: http.StatusUnauthorized,
errs.RetServerValidateFail: http.StatusBadRequest,
errs.RetUnknown: http.StatusInternalServerError,
}
// marshalError marshals an error.
func marshalError(err error, s Serializer) ([]byte, error) {
// All Serializers for tRPC-Go RESTful are expected to marshal proto messages.
// So it's better to convert a tRPC error to an *errors.Err.
terr := &errors.Err{
Code: int32(errs.Code(err)),
Message: errs.Msg(err),
}
return s.Marshal(terr)
}
// statusCodeFromError returns the status code from the error.
func statusCodeFromError(err error) int {
statusCode := http.StatusInternalServerError
if withStatusCode, ok := err.(*WithStatusCode); ok {
statusCode = withStatusCode.StatusCode
} else {
if statusFromMap, ok := httpStatusMap[errs.Code(err)]; ok {
statusCode = statusFromMap
}
}
return statusCode
}
// DefaultErrorHandler is the default ErrorHandler.
var DefaultErrorHandler = func(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
// get outbound Serializer
_, s := serializerForTranscoding(r.Header[headerContentType],
r.Header[headerAccept])
w.Header().Set(headerContentType, s.ContentType())
// marshal error
buf, merr := marshalError(err, s)
if merr != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(MarshalErrorContent))
return
}
// write response
w.WriteHeader(statusCodeFromError(err))
w.Write(buf)
}
// DefaultFastHTTPErrorHandler is the default FastHTTPErrorHandler.
var DefaultFastHTTPErrorHandler = func(ctx context.Context, requestCtx *fasthttp.RequestCtx, err error) {
// get outbound Serializer
_, s := serializerForTranscoding(
[]string{bytes2str(requestCtx.Request.Header.Peek(headerContentType))},
[]string{bytes2str(requestCtx.Request.Header.Peek(headerAccept))},
)
requestCtx.Response.Header.Set(headerContentType, s.ContentType())
// marshal error
buf, merr := marshalError(err, s)
if merr != nil {
requestCtx.Response.SetStatusCode(http.StatusInternalServerError)
requestCtx.Write([]byte(MarshalErrorContent))
return
}
// write response
requestCtx.SetStatusCode(statusCodeFromError(err))
requestCtx.Write(buf)
}