我有 func ,在调用函数之后,我想抛出一个 ApiException,但我没有抓住它。
第 1 步:
我在这里没有捕捉到 ApiException
FutureOr<void> login({String? user, String? password}) async {
try {
emit(LoadingLoginState());
await loginUseCase?.login(user, password);
} on ApiException catch (e) { // I'nt catch ApiException here
emit(ErrorLoginState(errorMessage: e.errorMessage));
} catch (_) {
emit(ErrorLoginState(errorMessage: S.current.connectionProblem));
}
}
第 2 步:
class LoginUseCase {
final LoginRepository _loginRepository;
LoginUseCase(this._loginRepository);
Future<LoginResponse?>? login(String? user, String? password) =>
_loginRepository.login(user, password);
}
第 3 步:
abstract class LoginRepository{
Future<LoginResponse?>? login(String? user, String? password);
}
第 4 步:
抛出 ApiException()
class UserRepoImpl implements LoginRepository {
UserApi? userApi;
UserRepoImpl({this.userApi});
@override
Future<LoginResponse?>? login(String? user, String? password) async {
throw ApiException();
}
}
答案 0 :(得分:0)
要异步捕获错误,您可以使用 .catchError
callApi().catchError((error){
// handle exception here
});
更新:您的代码
FutureOr<void> login({String? user, String? password}) async {
emit(LoadingLoginState());
await loginUseCase?.login(user, password)
?.catchError(error) {
if(error is ApiException) {
emit(ErrorLoginState(errorMessage: e.errorMessage));
} else {
emit(ErrorLoginState(errorMessage: S.current.connectionProblem));
}
}
}
答案 1 :(得分:0)
尝试使用像这样的 try-catch 块包装具体实现:
class LoginUseCase {
final LoginRepository _loginRepository;
LoginUseCase(this._loginRepository);
Future<LoginResponse?>? login(String? user, String? password) {
try{
_loginRepository.login(user, password);
} on ApiException catch(e){
print('API Exception caught');
}
}
}