如何在扑扑中捕捉异常?

时间:2018-10-09 12:58:17

标签: 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);
}

状态不为200时,CatchError不会捕获错误。捕获的Inshort错误不会打印。

4 个答案:

答案 0 :(得分:2)

尝试

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

catchError有时会有些棘手。 借助async / await,您可以像同步代码一样使用try / catch,通常更容易解决问题。

答案 1 :(得分:1)

要处理asyncawait函数中的错误,请使用try-catch

运行以下示例以查看如何处理异步函数中的错误。

Future<void> printOrderMessage() async {
  try {
    var order = await fetchUserOrder();
    print('Awaiting user order...');
    print(order);
  } catch (err) {
    print('Caught error: $err');
  }
}

Future<String> fetchUserOrder() {
  // Imagine that this function is more complex.
  var str = Future.delayed(
      Duration(seconds: 4),
      () => throw 'Cannot locate user order');
  return str;
}

Future<void> main() async {
  await printOrderMessage();
}

在异步函数中,您可以像在同步代码中一样编写try-catch clauses

答案 2 :(得分:0)

myText.substring(myText.indexOf('/') + 1)

答案 3 :(得分:0)

假设这是您抛出异常的函数:

Future<void> foo() async {
  throw Exception('FooException');
}

您可以在 try-catch 上使用 catchError 块或 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`.
    }
    
  • 使用catchError

    await foo().catchError(print);