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

问题描述 投票:0回答:2

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

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

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

exception dart flutter
2个回答
0
投票

而不是使用rethrow或抛出新的异常。返回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
})

0
投票

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');
      }
© www.soinside.com 2019 - 2024. All rights reserved.