P-R*_*RAD 7 model-view-controller dart flutter
这是我的异常类。异常类已经由flutter的抽象异常类实现。我错过了什么吗?
class FetchDataException implements Exception {
final _message;
FetchDataException([this._message]);
String toString() {
if (_message == null) return "Exception";
return "Exception: $_message";
}
}
void loginUser(String email, String password) {
_data
.userLogin(email, password)
.then((user) => _view.onLoginComplete(user))
.catchError((onError) => {
print('error caught');
_view.onLoginError();
});
}
Future < User > userLogin(email, password) async {
Map body = {
'username': email,
'password': password
};
http.Response response = await http.post(apiUrl, body: body);
final responseBody = json.decode(response.body);
final statusCode = response.statusCode;
if (statusCode != HTTP_200_OK || responseBody == null) {
throw new FetchDataException(
"An error occured : [Status Code : $statusCode]");
}
return new User.fromMap(responseBody);
}
Run Code Online (Sandbox Code Playgroud)
当状态不是200时,CatchError不会捕获错误。捕获的Inshort错误不会被打印。
Cop*_*oad 21
假设这是您的函数抛出异常:
Future<void> foo() async {
throw Exception('FooException');
}
Run Code Online (Sandbox Code Playgroud)
您可以使用try-catchblock 或catchErroron the,Future因为两者都执行相同的操作。
使用try-catch
try {
await foo();
} on Exception catch (e) {
print(e); // Only catches an exception of type `Exception`.
} catch (e) {
print(e); // Catches all types of `Exception` and `Error`.
}
Run Code Online (Sandbox Code Playgroud)
使用catchError
await foo().catchError(print);
Run Code Online (Sandbox Code Playgroud)
Gün*_*uer 14
尝试
void loginUser(String email, String password) async {
try {
var user = await _data
.userLogin(email, password);
_view.onLoginComplete(user);
});
} on FetchDataException catch(e) {
print('error caught: $e');
_view.onLoginError();
}
}
Run Code Online (Sandbox Code Playgroud)
catchError有时候做起来有点棘手。使用async/,await您可以将try/ catch喜欢与同步代码配合使用,通常更容易正确。