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


前言

我们知道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 进行统一错误处理。但是这里面并没有对与成功的请求做一个数据格式包装,如果想对正确的请求做一个数据包装一般在网关那层进行处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java + gRPC + grpc-gateway 的实践主要分为以下几个步骤: 1. 定义 proto 文件 在 proto 文件中定义需要调用的服务以及方法,同时指定请求和响应的数据类型。例如: ``` syntax = "proto3"; package example; service ExampleService { rpc ExampleMethod (ExampleRequest) returns (ExampleResponse) {} } message ExampleRequest { string example_field = 1; } message ExampleResponse { string example_field = 1; } ``` 2. 使用 protoc 编译 proto 文件 使用 protoc 编译 proto 文件,生成 Java 代码。例如: ``` protoc --java_out=./src/main/java ./example.proto ``` 3. 实现 gRPC 服务 在 Java 代码中实现定义的 gRPC 服务,例如: ``` public class ExampleServiceImpl extends ExampleServiceGrpc.ExampleServiceImplBase { @Override public void exampleMethod(ExampleRequest request, StreamObserver<ExampleResponse> responseObserver) { // 实现具体逻辑 ExampleResponse response = ExampleResponse.newBuilder().setExampleField("example").build(); responseObserver.onNext(response); responseObserver.onCompleted(); } } ``` 4. 启动 gRPC 服务器 使用 gRPC 提供的 ServerBuilder 构建 gRPC 服务器,并启动服务器。例如: ``` Server server = ServerBuilder.forPort(8080).addService(new ExampleServiceImpl()).build(); server.start(); ``` 5. 集成 grpc-gateway 使用 grpc-gateway 可以将 gRPC 服务转换为 HTTP/JSON API。在 proto 文件中添加以下内容: ``` import "google/api/annotations.proto"; service ExampleService { rpc ExampleMethod (ExampleRequest) returns (ExampleResponse) { option (google.api.http) = { post: "/example" body: "*" }; } } ``` 在 Java 代码中添加以下内容: ``` Server httpServer = ServerBuilder.forPort(8081).addService(new ExampleServiceImpl()).build(); httpServer.start(); String grpcServerUrl = "localhost:8080"; String httpServerUrl = "localhost:8081"; ProxyServerConfig proxyConfig = new ProxyServerConfig(grpcServerUrl, httpServerUrl, "/example"); HttpProxyServer httpProxyServer = new HttpProxyServer(proxyConfig); httpProxyServer.start(); ``` 6. 测试 使用 HTTP/JSON API 调用 gRPC 服务,例如: ``` POST http://localhost:8081/example Content-Type: application/json { "example_field": "example" } ``` 以上就是 Java + gRPC + grpc-gateway 的实践步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值