grpc / grpc-dart

The Dart language implementation of gRPC.
https://pub.dev/packages/grpc
Apache License 2.0
860 stars 271 forks source link

Send trailers included on GrpcError object #538

Closed ruicraveiro closed 2 years ago

ruicraveiro commented 2 years ago

A previous PR #493 solved the problem of receiving trailers within the GrpcError object from the client. It works well with servers built in other languages that send those trailers. But the piece that was still missing is the inclusion of those trailers when this library is being used on the server.

So, if the following method on the server throws an error containing trailers:

    throw GrpcError.custom(
      StatusCode.internal,
      'This error should contain trailers',
      null,
      null,
      {
        'key1': 'value1',
        'key2': 'value2',
      },
    );

The client should be receiving the trailers, just like it would from a server developed on any other gRPC server language. The following client-side code should print It has the trailers: {key1: value1, key2: value2}.

Future<void> main(List<String> args) async {
  final channel = ClientChannel(
    'localhost',
    port: 50051,
    options: ChannelOptions(
      credentials: ChannelCredentials.insecure(),
      codecRegistry:
          CodecRegistry(codecs: const [GzipCodec(), IdentityCodec()]),
    ),
  );
  final stub = GreeterClient(channel);

  final name = args.isNotEmpty ? args[0] : 'world';

  try {
    final response = await stub.sayHello(
      HelloRequest()..name = name,
      options: CallOptions(compression: const GzipCodec()),
    );
    print('Greeter client received: ${response.message}');
  } on GrpcError catch (e) {
    print('It has the trailers: ${e.trailers}');
  }
  await channel.shutdown();
}

I added a new test on [round_trip_test.dart] called trailers on server GrpcError, which is green along with all other tests.

ruicraveiro commented 2 years ago

Hi @mraleph, can you find some time to look at this? It's actually a relatively simple change and the greatest number of lines added were to set up the new unit test that I included.