Why do I can't catch Grpc Error in FLutter?

Viewed 822

My app send image from client to server with grpc, but I cannot catch that error, here is my code:

var response;
    try {
    response = await dataService.sendFace(
        listImageToListFaceRecImage(
            dataImages, dataTrackID, dataRect, dataLandMark),
        dataDeviceID,
        dataDoorID);
    } catch(e) {
      print('Caught error: $e');
    }
    response.first.then((value) {
      isSending = false;
      print("receive");
      print(value.result);
      if (value.result.isNotEmpty) {
        Map<String, dynamic> result =
        (jsonDecode(value.result) as List<dynamic>)[0];
        String personCode = result['person_code'];
        replyTo.send([personCode, capturedFaceImage]);
      }
    });

The result I want is:

Caught error: //Error here

But it show this error and I dont know why it cannot catch:

gRPC Error (14, Error connecting: SocketException: Connection failed (OS Error: Network is unreachable, errno = 101), address = 172.16.0.39, port = 4001)

1 Answers

This can be solved catching the error as GrpcError, then you can access all the parts of the error:

try {
response = await dataService.sendFace(
    listImageToListFaceRecImage(
        dataImages, dataTrackID, dataRect, dataLandMark),
    dataDeviceID,
    dataDoorID);
} on GrpcError catch(e) {
    print('Caught error: ${e.message}');
} catch (e){
    // any other error
}
...

also don´t forget the import: import 'package:grpc/grpc.dart';

you have access now to all the error fields:

final int code;
final String? message;
final Object? rawResponse;
final Map<String, String>? trailers;
final List<GeneratedMessage>? details;

ref: https://github.com/grpc/grpc-dart/blob/master/lib/src/shared/status.dart

Related