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

标签 flutter dart exception

我抛出如下异常;

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

关于flutter - 如何解析 Dart/Flutter 中的异常对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70979801/

相关文章:

flutter - 如何使用Charts_flutter库创建自定义的Legend xContentBuilder,以显示和隐藏根据选择而产生的系列?

flutter - 无法在Flutter中滚动ListView

flutter - 如何在一个 ListView 中使用多个 StreamBuilder

flutter - 如何使用flutter和Dio为POST设置 header

flutter - 如何使用 dart :js? 将选项传递给 javascript 函数

Flutter FittedBox/Expand/Flex 基于列中的小部件

flutter - 在 flutter 中创建自定义下拉列表 - 或者如何将自定义下拉选项放在其他所有内容之上的图层中

android - 在启用测试模式后,Gradle构建失败?

c# - 发送 webRequest 时出错

java - 异常(org.openqa.selenium.NoSuchWindowException): using Selenium WebDriver with Java in Internet Explorer