我正在使用go标准库中的rpc软件包,并且希望能够通过RPC调用返回我的自定义错误。
我在下面有自定义错误类:
const (
UNAVAILABLE = "unavailable"
GETERROR = "get-error"
OTHER = "generic-error"
)
type CustomError struct {
ErrorCode string
Msg string
}
func (e *CustomError) Error() string {
return fmt.Sprintf("Error type: %s, Msg: %s", e.ErrorCode, e.Msg)
}
以及以下RPC端点:
func (service *RpcService) Get(args *Args, reply *string) error {
....
do something
...
if err != nil {
return CustomError{ErrorCode: GETERROR, Msg: ""}
}
return nil
}
问题是当我在客户端检索错误时,我收到rpc.ServerError。我尝试将其强制转换为自定义错误类型,但我惊慌地说interface conversion: error is rpc.ServerError, not *CustomError
。基本上,我的问题是:如何从RPC调用中传播自定义错误类型。
答案 0 :(得分:0)
标准库以字符串rpc.ServerError
的形式返回错误。
因此在您的代码中,您从客户端得到的错误将类似于:
"Error type: unavailable, Msg: "
如果您想将错误与client.Get区别开,可以使CustomError.Error()更简单,例如:Unavailable: something wrong
,然后可以将其视为字符串。
或者您可以添加一个额外的字符串返回值以区分结果。