-
Notifications
You must be signed in to change notification settings - Fork 11
Advanced Error Mocking
gRPC supports returning rich errors through the status package. Let's start by examining the type status.Status
proto definition:
message Status {
int32 code = 1;
string message = 2;
repeated google.protobuf.Any details = 3;
}
The code
and message
fields are straightforward. The code must be greater than 0 (0 is response OK = Success). See full list of error codes. The details
field adds a bit of complexity. The repeated google.protobuf.Any details
translates into func (s *Status) Details() []interface{}
in Go. It means that it can contain any proto.Message
.
The stubs management REST API allows the definition of rich error responses. All we need to do is provide the type the detail. Ex.:
{
"fullMethod": "/carvalhorr.greeter.UserService/AddUser",
"request": {
"match": "exact",
"content": {
"name": "",
"age": 0
},
"metadata": {}
},
"response": {
"type": "error",
"content": {},
"error": {
"code": 1,
"message": "",
"details": {
"spec": {
"import": "google.golang.org/genproto/googleapis/rpc/errdetails",
"type": "BadRequest"
},
"values": [
{
"value": {
"field_violations": [
{
"field": "Name",
"description": "Name is mandatory"
},
{
"field": "Age",
"description": "Age must be a positive number"
}
]
}
}
]
}
}
}
}
The response.error.details.spec
field is how we set the stub with any custom proto.Message
. This field contains two fields: import
and type
. They correspond to the go import path and the type within that import respectively to the proto.Message
. Note that this is not the proto definition, but the generated go type instead.
It is possible to have different values in each entry of response.error.details
. To do so it is necessary to use the value's specOverride
field, providing alternative import
and type
.