如何在 Flutter 中传递(在方法堆栈中)异常?

Mar*_*lho 6 exception dart flutter

我正在尝试制作一个使用“HTTP Get”通信登录 Flutter 的 REST 应用程序。虽然导入“http/http.dart”包并运行 http 类方法没有问题,但我在 Dart/Flutter 中遇到了异常处理问题。我创建了一个调用 http 的方法,但是如果由于任何原因连接中断,它自然会返回一个“SocketException”异常。我在发出 get 请求的同一方法中处理异常没有问题,但是如果我尝试将它在调用方方法堆栈中传递给父方法,我就无法再次捕获它。我找到了“rethrow”关键字,但到目前为止,没有成功重新抛出异常。下面是我在代码中使用的一些方法,包括 login 方法和 caller 方法:

static Future<JsonEnvelop> loginUser(String email, String passwd) async {

    List<int> content = Utf8Encoder().convert(passwd);
    crypto.Digest digest = crypto.md5.convert(content);

    String url = _baseUrl + _loginUrl + email + "/" + digest.toString();

    http.Response response;
    try {
      response = await http.get(url);
    } on SocketException catch(e) {
      rethrow;
    }

    if(response != null && response.statusCode == 200) {
      return JsonEnvelop.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to login');
    }
  }

void onVerifyCodeBtnPressed(BuildContext context) {
    if (_formKey.currentState.validate()) {
      String email = _emailController.text;
      String passwd = _passwdController.text;

      Future<JsonEnvelop> envelop;
      try {
        envelop = RemoteUserServices.loginUser(
            email, passwd);
      } on SocketException {
        throw Exception('Internet is down');
      }
      Scaffold.of(context).showSnackBar(SnackBar(content: Text('Login to your account')));

      envelop.then((JsonEnvelop envelop) {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: new Text("Login"),
              content: new Text("Login Successful"),
              actions: <Widget>[
                new FlatButton(
                  child: new Text("OK"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                )
              ],
            );
          }
        );
      });
    } else {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: new Text("Missing data"),
            content: new Text("Type your email and password in the fields"),
            actions: <Widget>[
              new FlatButton(
                child: new Text("OK"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              )
            ],
          );
        }
      );
    }
  }
Run Code Online (Sandbox Code Playgroud)

在这种情况下可能有什么问题?我希望创建一个对话框警告用户互联网已关闭。

Gün*_*uer 6

try/catch异步代码的例外情况仅适用于具有 的函数async,否则您需要传递回调或在返回值上onError使用,这显然更难以正确执行。.catchError(...)Future

  void onVerifyCodeBtnPressed(BuildContext context) async { // added async 
    if (_formKey.currentState.validate()) {
      String email = _emailController.text;
      String passwd = _passwdController.text;

      Future<JsonEnvelop> envelop;
      try {
        envelop = await RemoteUserServices.loginUser( // added `await`
            email, passwd);
      } on SocketException {
        throw Exception('Internet is down');
      }
Run Code Online (Sandbox Code Playgroud)


Fil*_*cks 4

而不是使用重新抛出或抛出新的异常。返回一个 Future.error()

Future<bool> methodThatErrorsOnCall() {
 return Future.error();
}
...
...
methodThatErrorsOnCall.catchError((e) {
  print('I want to show a dialog: ${e.error}');     // callback fires.
  return false;                                     // Future completes with false
})
Run Code Online (Sandbox Code Playgroud)