1

I have the following simple service definition:

service Echo {
    rpc echo (In) returns (Out) {}
}

message In {
    string text = 1;
}

message Out {
    string text = 1;
}

message Error {
    int32 status = 1;
}

As you see, I have a custom Error definition. This holds a service-specific status code. The service is evaluating the given text and returning an error if the text is not appropriate. In my Java application, I am doing the following to return an Error object:

import com.google.protobuf.Any;
import com.google.rpc.Code;
import com.google.rpc.Status;

...

final StreamObserver<Out> response = ...; // as given by the library
final Error error = Error.newBuilder().setStatus(55).build(); // this creates a custom Error object, see .proto

response.onError(StatusProto.toStatusRuntimeException(Status.newBuilder()
        .setCode(Code.INVALID_ARGUMENT.getNumber())
        .setMessage("This argument is invalid.")
        .addDetails(Any.pack(error))
        .build()));

My question now is: How can I get the custom Error payload in my JS application?

var request = new In();
request.setText('Some text which will be evaluated at the server.');

client.echo(request, {}, (error, response) => {
   // if (55 = error.details.status) { ... }
});

I am currently working with the JS version of grpc-web, though I might migrate to TS soon.

1 Answers1

0

Here's an example on how to consume the error object in a unary RPC: https://github.com/grpc/grpc-web/blob/master/net/grpc/gateway/examples/echo/echoapp.js#L71-L74

In short, you do

if (err) {
  // console.log(err.code)
  // console.log(err.message)
}
Stanley Cheung
  • 347
  • 1
  • 3