grpc-gateway ServeMux 使用hook进行统一错误处理

发布于:2023-01-01 ⋅ 阅读:(769) ⋅ 点赞:(0)


前言

我们知道grpc 接口返回是有两个参数的 一个是 data,而另一个就是error,但是转成http 之后这个error 应该怎么办呢?所以咱们需要对grpc 的error 进行统一的错误处理。
当然grpc- gateway里面是又默认的数据格式,可是有些时候我们并不满足这种格式所以我们得自定义。


一、 With.ErrorHandlerFunc

咱们先看 ServerMux中有哪些hooks
在这里插入图片描述
这是 grpc-gateway 的请求多路复用器。它将 http 请求与模式匹配并调用相应的处理程序,咱们今天需要用到的就是 errorHandler

  1. 查看默认的错误处理 是怎么样的
    下面是截取了 grpc- gateway中的errors.go 文件中的默认错误处理代码
    // DefaultHTTPErrorHandler is the default error handler.
    // If "err" is a gRPC Status, the function replies with the status code 		mapped by HTTPStatusFromCode.
    // If "err" is a HTTPStatusError, the function replies with the status code provide by that struct. This is
    // intended to allow passing through of specific statuses via the function set via WithRoutingErrorHandler
    // for the ServeMux constructor to handle edge cases which the standard mappings in HTTPStatusFromCode
    // are insufficient for.
    // If otherwise, it replies with http.StatusInternalServerError.
    //
    // The response body written by this function is a Status message marshaled by the Marshaler.
    func DefaultHTTPErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) {
    // return Internal when Marshal failed
    const fallback = `{"code": 13, "message": "failed to marshal error message"}`
    
    var customStatus *HTTPStatusError
    if errors.As(err, &customStatus) {
    	err = customStatus.Err
    }
    
    s := status.Convert(err)
    pb := s.Proto()
    
    w.Header().Del("Trailer")
    w.Header().Del("Transfer-Encoding")
    
    contentType := marshaler.ContentType(pb)
    w.Header().Set("Content-Type", contentType)
    
    if s.Code() == codes.Unauthenticated {
    	w.Header().Set("WWW-Authenticate", s.Message())
    }
    
    buf, merr := marshaler.Marshal(pb)
    if merr != nil {
    	grpclog.Infof("Failed to marshal error message %q: %v", s, merr)
    	w.WriteHeader(http.StatusInternalServerError)
    	if _, err := io.WriteString(w, fallback); err != nil {
    		grpclog.Infof("Failed to write response: %v", err)
    	}
    	return
    }
    
    md, ok := ServerMetadataFromContext(ctx)
    if !ok {
    	grpclog.Infof("Failed to extract ServerMetadata from context")
    }
    
    handleForwardResponseServerMetadata(w, mux, md)
    
    // RFC 7230 https://tools.ietf.org/html/rfc7230#section-4.1.2
    // Unless the request includes a TE header field indicating "trailers"
    // is acceptable, as described in Section 4.3, a server SHOULD NOT
    // generate trailer fields that it believes are necessary for the user
    // agent to receive.
    doForwardTrailers := requestAcceptsTrailers(r)
    
    if doForwardTrailers {
    	handleForwardResponseTrailerHeader(w, md)
    	w.Header().Set("Transfer-Encoding", "chunked")
    }
    
    st := HTTPStatusFromCode(s.Code())
    if customStatus != nil {
    	st = customStatus.HTTPStatus
    }
    
    w.WriteHeader(st)
    if _, err := w.Write(buf); err != nil {
    	grpclog.Infof("Failed to write response: %v", err)
    }
    
    if doForwardTrailers {
    	handleForwardResponseTrailer(w, md)
    }
    }
    
    上面是对请求头做了一些处理,以及获取了error 的信息 然后在通过 HTTPStatusFromCode 去对于请求状态的一个改变,然后使用WriteHeader 函数写入本次请求的状态码,Write写入出去的值,那么上面是简单的介绍Default 操作是怎么做的,接下来我们自定义一个HTTPErrorHandler。

二、自定义HTTPErrorHandler

1.使用runtime.NewServeMux

在这里插入图片描述
errorHandler 就是我们需要自定义的错误处理函数,通过WithErrorHandler 去初始化Mux 中的 errorHandler

2.errorHandler 函数编写

func errorHandler(_ context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, writer http.ResponseWriter, request *http.Request, err error) 

我们先定义一个统一的返回数据结构体并初始化

var resp = &utils.Response{
		Success:   false,
		ErrorCode: 500,
		Message:   "",
		Data:      nil,
	}

将error进行解析然后赋值给resp 设置请求头content-type

	s := status.Convert(err)
	pb := s.Proto()
	resp.Message = pb.GetMessage()
	resp.ErrorCode = pb.GetCode()
	contentType := marshaler.ContentType(pb)
	writer.Header().Set("Content-Type", contentType)

下面就是对结构体进行Marshaler

	buf, merr := marshaler.Marshal(resp)
	if merr != nil {
		grpclog.Infof("Failed to marshal error message %q: %v", s, merr)
		writer.WriteHeader(http.StatusInternalServerError)
		if _, err := io.WriteString(writer, fallback); err != nil {
			grpclog.Infof("Failed to write response: %v", err)
		}
		return
	}

下面就是对 code码进行一个转换 ,查找相应的http 状态码

	st := utils.HTTPStatusFromCode(s.Code())
	writer.WriteHeader(st)
	if _, err := writer.Write(buf); err != nil {
		grpclog.Infof("Failed to write response: %v", err)
	}
func HTTPStatusFromCode(code codes.Code) int {
	switch code {
	case codes.OK:
		return http.StatusOK
	case codes.Canceled:
		return http.StatusRequestTimeout
	case codes.Unknown:
		return http.StatusInternalServerError
	case codes.InvalidArgument:
		return http.StatusBadRequest
	case codes.DeadlineExceeded:
		return http.StatusGatewayTimeout
	case codes.ResourceExhausted:
		return http.StatusTooManyRequests
	case codes.FailedPrecondition:
		return http.StatusBadRequest
	case codes.OutOfRange:
		return http.StatusBadRequest
	case codes.Unimplemented:
		return http.StatusNotImplemented
	case codes.Internal:
		return http.StatusInternalServerError
	case codes.Unavailable:
		return http.StatusServiceUnavailable
	case codes.DataLoss:
		return http.StatusInternalServerError
	}
	grpclog.Infof("Unknown gRPC error code: %v", code)
	return http.StatusInternalServerError
}

错误演示:
在这里插入图片描述


总结

以上就是对于grpc-gateway 通过 runtime.WithErrorHandler 进行统一错误处理。但是这里面并没有对与成功的请求做一个数据格式包装,如果想对正确的请求做一个数据包装一般在网关那层进行处理。