| 1 |
package runtime |
| 2 |
|
| 3 |
import ( |
| 4 |
"io" |
| 5 |
"net/http" |
| 6 |
|
| 7 |
"github.com/golang/protobuf/proto" |
| 8 |
"golang.org/x/net/context" |
| 9 |
"google.golang.org/grpc/codes" |
| 10 |
"google.golang.org/grpc/grpclog" |
| 11 |
"google.golang.org/grpc/status" |
| 12 |
) |
| 13 |
|
| 14 |
// HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status. |
| 15 |
func HTTPStatusFromCode(code codes.Code) int { |
| 16 |
switch code { |
| 17 |
case codes.OK: |
| 18 |
return http.StatusOK |
| 19 |
case codes.Canceled: |
| 20 |
return http.StatusRequestTimeout |
| 21 |
case codes.Unknown: |
| 22 |
return http.StatusInternalServerError |
| 23 |
case codes.InvalidArgument: |
| 24 |
return http.StatusBadRequest |
| 25 |
case codes.DeadlineExceeded: |
| 26 |
return http.StatusRequestTimeout |
| 27 |
case codes.NotFound: |
| 28 |
return http.StatusNotFound |
| 29 |
case codes.AlreadyExists: |
| 30 |
return http.StatusConflict |
| 31 |
case codes.PermissionDenied: |
| 32 |
return http.StatusForbidden |
| 33 |
case codes.Unauthenticated: |
| 34 |
return http.StatusUnauthorized |
| 35 |
case codes.ResourceExhausted: |
| 36 |
return http.StatusForbidden |
| 37 |
case codes.FailedPrecondition: |
| 38 |
return http.StatusPreconditionFailed |
| 39 |
case codes.Aborted: |
| 40 |
return http.StatusConflict |
| 41 |
case codes.OutOfRange: |
| 42 |
return http.StatusBadRequest |
| 43 |
case codes.Unimplemented: |
| 44 |
return http.StatusNotImplemented |
| 45 |
case codes.Internal: |
| 46 |
return http.StatusInternalServerError |
| 47 |
case codes.Unavailable: |
| 48 |
return http.StatusServiceUnavailable |
| 49 |
case codes.DataLoss: |
| 50 |
return http.StatusInternalServerError |
| 51 |
} |
| 52 |
|
| 53 |
grpclog.Printf("Unknown gRPC error code: %v", code) |
| 54 |
return http.StatusInternalServerError |
| 55 |
} |
| 56 |
|
| 57 |
var ( |
| 58 |
// HTTPError replies to the request with the error. |
| 59 |
// You can set a custom function to this variable to customize error format. |
| 60 |
HTTPError = DefaultHTTPError |
| 61 |
// OtherErrorHandler handles the following error used by the gateway: StatusMethodNotAllowed StatusNotFound and StatusBadRequest |
| 62 |
OtherErrorHandler = DefaultOtherErrorHandler |
| 63 |
) |
| 64 |
|
| 65 |
type errorBody struct { |
| 66 |
Error string `protobuf:"bytes,1,name=error" json:"error"` |
| 67 |
Code int32 `protobuf:"varint,2,name=code" json:"code"` |
| 68 |
} |
| 69 |
|
| 70 |
//Make this also conform to proto.Message for builtin JSONPb Marshaler |
| 71 |
func (e *errorBody) Reset() { *e = errorBody{} } |
| 72 |
func (e *errorBody) String() string { return proto.CompactTextString(e) } |
| 73 |
func (*errorBody) ProtoMessage() {} |
| 74 |
|
| 75 |
// DefaultHTTPError is the default implementation of HTTPError. |
| 76 |
// If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode. |
| 77 |
// If otherwise, it replies with http.StatusInternalServerError. |
| 78 |
// |
| 79 |
// The response body returned by this function is a JSON object, |
| 80 |
// which contains a member whose key is "error" and whose value is err.Error(). |
| 81 |
func DefaultHTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, _ *http.Request, err error) { |
| 82 |
const fallback = `{"error": "failed to marshal error message"}` |
| 83 |
|
| 84 |
w.Header().Del("Trailer") |
| 85 |
w.Header().Set("Content-Type", marshaler.ContentType()) |
| 86 |
|
| 87 |
s, ok := status.FromError(err) |
| 88 |
if !ok { |
| 89 |
s = status.New(codes.Unknown, err.Error()) |
| 90 |
} |
| 91 |
|
| 92 |
body := &errorBody{ |
| 93 |
Error: s.Message(), |
| 94 |
Code: int32(s.Code()), |
| 95 |
} |
| 96 |
|
| 97 |
buf, merr := marshaler.Marshal(body) |
| 98 |
if merr != nil { |
| 99 |
grpclog.Printf("Failed to marshal error message %q: %v", body, merr) |
| 100 |
w.WriteHeader(http.StatusInternalServerError) |
| 101 |
if _, err := io.WriteString(w, fallback); err != nil { |
| 102 |
grpclog.Printf("Failed to write response: %v", err) |
| 103 |
} |
| 104 |
return |
| 105 |
} |
| 106 |
|
| 107 |
md, ok := ServerMetadataFromContext(ctx) |
| 108 |
if !ok { |
| 109 |
grpclog.Printf("Failed to extract ServerMetadata from context") |
| 110 |
} |
| 111 |
|
| 112 |
handleForwardResponseServerMetadata(w, mux, md) |
| 113 |
handleForwardResponseTrailerHeader(w, md) |
| 114 |
st := HTTPStatusFromCode(s.Code()) |
| 115 |
w.WriteHeader(st) |
| 116 |
if _, err := w.Write(buf); err != nil { |
| 117 |
grpclog.Printf("Failed to write response: %v", err) |
| 118 |
} |
| 119 |
|
| 120 |
handleForwardResponseTrailer(w, md) |
| 121 |
} |
| 122 |
|
| 123 |
// DefaultOtherErrorHandler is the default implementation of OtherErrorHandler. |
| 124 |
// It simply writes a string representation of the given error into "w". |
| 125 |
func DefaultOtherErrorHandler(w http.ResponseWriter, _ *http.Request, msg string, code int) { |
| 126 |
http.Error(w, msg, code) |
| 127 |
} |