我抛出如下异常;
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/