在golang项目中,通过grpc开发时,对于非法传入的参数、解析失败、返回异常时,虽然使用的是自定义的状态码,如果不做特殊处理,grpc默认会使用其内部的状态码进行拦截。
如果想要使用自定义的错误码,应该如何处理呢?这里提供一种方式可以自由使用自定义的状态码,虽然不能从全局拦截grpc状态码,但也能够做到简洁方便地处理自定义状态码,具体只需在返回error之前,通过status.Errorf()传入自定义错误码和错误信息描述即可。
import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
err = status.Errorf(codes.Code(resp.ErrNum), errcode.GetCodeDesc(int(resp.ErrNum)))
其中,resp表示返回结构,ErrNum表示错误码,GetCodeDesc函数通过错误码返回对应的错误信息描述。status.Errorf函数定义如下:
// A Code is an unsigned 32-bit error code as defined in the gRPC spec.
type Code uint32
// Errorf returns Error(c, fmt.Sprintf(format, a...)).
func Errorf(c codes.Code, format string, a ...interface{}) error {
return Error(c, fmt.Sprintf(format, a...))
}
参考
https://avi.im/grpc-errors/
gRPC服务器错误处理程序golang