Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to parse exception object in Dart/Flutter

I am throwing exception like below;

 if (response.statusCode == 400) {
     LoginErrorResponse loginErrorResponse = LoginErrorResponse.fromMap(responseMap);
     List<String> errorList = loginErrorResponse.getErrorList();
     throw Exception(errorList);
  }

And catching as below;

try {
        AuthenticatedUser user = await reClient.login("test", "test");
      
      } on Exception catch (ex, _) {
         // parse from ex to -> List<string>?
      }

I could not find a way to parse thrown exception into the List type.
In debugger I can access to ex.message, but in the code it is not exposed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What can I do?

>Solution :

You need to subclass Exception and create a custom one:

class LoginApiException implements Exception {
  LoginApiException(this.errors);

  final List<String> errors;
}

then:

if (response.statusCode == 400) {
    LoginErrorResponse loginErrorResponse = LoginErrorResponse.fromMap(responseMap);
    List<String> errorList = loginErrorResponse.getErrorList();
    throw LoginApiException(errorList);
}
try {
  AuthenticatedUser user = await reClient.login("test", "test");
} on LoginApiException catch (ex, _) {
     print(ex.errors);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading