如何解析 Dart/Flutter 中的异常对象

How to parse exception object in Dart/Flutter

我正在抛出如下异常;

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

并如下捕捉;

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

我找不到将抛出的异常解析为 List 类型的方法。 在调试器中我可以访问 ex.message,但在代码中它没有暴露。

我能做什么?

您需要继承 Exception 并创建一个自定义的:

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

  final List<String> errors;
}

然后:

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);
}