如何在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);
}

最新更新