Decode a response from a catch in Dart

2019-08-31 03:51发布

问题:

I try to decode the response returned from a catch, here is what I tried :

try{
  ...
} catch (err) {
    //JsonCodec codec = new JsonCodec(); // doesn't work
    //var decoded = codec.decode(err);
    ...
 }

Error: type '_Exception' is not a subtype of type 'String'

print(err) :

Exception: { "error": { "code": "invalid_expiry_year" } }

I would like to get the value of "code", I tried many things but it doesn't work,

Any idea?

 print(err.code);

then I get :

回答1:

You could get the message property and jsonDecode it.

try {
} catch (e) {
  var message = e.message; // not guaranteed to work if the caught exception isn't an _Exception instance
  var decoded = jsonDecode(message);
  print(decoded['error']['code'])'
}

All of this strikes as a misuse of Exception. Note that you generally don't want to throw Exception(message);. Putting a json encoded message in there is not the best way to communicate details about the exception. Instead, write a custom implementation of Exception and catch the specific type.

class InvalidDataException implements Exception {
  final String code;
  InvalidDataException(this.code);
}

try {
} on InvalidDataException catch(e) {
  print(e.code); // guaranteed to work, we know the type of the exception
}

See the docs for Exception:

Creating instances of Exception directly with new Exception("message") is discouraged, and only included as a temporary measure during development, until the actual exceptions used by a library are done.

See also https://www.dartlang.org/guides/language/effective-dart/usage#avoid-catches-without-on-clauses



回答2:

I finally figured out a solution :

catch (response) {
    var err=response.toString().replaceAll('Exception: ', '');
   final json=JSON.jsonDecode(err);
   print(json['error']['code']);
}


标签: dart