How do you get the message from PlatformException?

Viewed 359

I made a https call in cloud functions and threw an error if a condition fails, in flutter i handled it successfully and it shows me this : PlatformException(functionsError, Cloud function failed with exception., {code: FAILED_PRECONDITION, details: null, message: Error: Your card was declined.})

but i want to know how i can get just the message part to display to the user? so far i already tried e.message but that didnt work

CloudFunctions(app: Firebase.app(), region: 'asia-southeast2')
      .getHttpsCallable(functionName: 'addPayment')
      .call({
    'paymentMethodId': paymentMethod.id,
    'userid': FirebaseAuth.instance.currentUser.uid,
  }).catchError((e) => print('ERROR $e'));

this is my function

2 Answers

The PlatformException class has the following properties:

  • code → String An error code. final

  • details → dynamic Error details, possibly null. final

  • hashCode → int The hash code for this object. [...] read-only, inherited

  • message → String A human-readable error message, possibly null. final

  • runtimeType → Type A representation of the runtime type of the object. read-only, inherited

To handle it you would do:

.catchError((e) {
    if (e is PlatformException){
         // Show e.details['message']
    }else{
         print('ERROR $e');
    }
});
.catchError((error) {
  String errorMessage = error.toString();
  if (error is PlatformException &&
      error.message != null &&
      error.message!.isNotEmpty) {
    errorMessage = error.message!;
  }
}
Related