Home > Software design >  How to parse exception object in Dart/Flutter
How to parse exception object in Dart/Flutter

Time:02-04

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.

What can I do?

CodePudding user response:

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);
}
  •  Tags:  
  • Related