Exception 如何在颤振中传递(在方法堆栈中)异常?

Exception 如何在颤振中传递(在方法堆栈中)异常?,exception,dart,flutter,Exception,Dart,Flutter,我正在尝试制作一个REST应用程序,它使用“HTTP Get”通信登录到Flatter中。而导入“http/http.dart”包和 在运行http类方法时,我在Dart/FLIFT中遇到了异常处理问题。我创建了一个调用http的方法,但是如果 由于任何原因,连接中断,它自然会返回“SocketException”异常。我用同样的方法处理异常没有问题 谁发出了get请求,但是如果我试图在调用方方法堆栈中将它传递给父方法,我就再也抓不到它了。我找到了 “rethrow”关键字,但到目前为止,没有成

我正在尝试制作一个REST应用程序,它使用“HTTP Get”通信登录到Flatter中。而导入“http/http.dart”包和 在运行http类方法时,我在Dart/FLIFT中遇到了异常处理问题。我创建了一个调用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();
                },
              )
            ],
          );
        }
      );
    }
  }
静态未来登录用户(字符串电子邮件、字符串密码)异步{
列表内容=Utf8Encoder().convert(passwd);
crypto.Digest Digest=crypto.md5.convert(内容);
字符串url=_baseUrl+_loginUrl+电子邮件+“/”+摘要.toString();
http.响应;
试一试{
response=wait http.get(url);
}关于SocketException捕捉(e){
改头换面;
}
if(response!=null&&response.statusCode==200){
返回jsonevelop.fromJson(json.decode(response.body));
}否则{
抛出异常('登录失败');
}
}
void onVerifyCodeBtnPressed(构建上下文){
if(_formKey.currentState.validate()){
字符串email=\u emailController.text;
字符串passwd=\u passwdController.text;
未来包络线;
试一试{
Envelope=RemoteUserServices.loginUser(
电子邮件(passwd);
}论SocketException{
抛出异常(“Internet已关闭”);
}
showSnackBar(SnackBar(内容:Text('Login to your account'));
信封。然后((jsonevelop信封){
显示对话框(
上下文:上下文,
生成器:(BuildContext上下文){
返回警报对话框(
标题:新文本(“登录”),
内容:新文本(“登录成功”),
行动:[
新扁平按钮(
子项:新文本(“确定”),
已按下:(){
Navigator.of(context.pop();
},
)
],
);
}
);
});
}否则{
显示对话框(
上下文:上下文,
生成器:(BuildContext上下文){
返回警报对话框(
标题:新文本(“缺失数据”),
内容:新文本(“在字段中键入您的电子邮件和密码”),
行动:[
新扁平按钮(
子项:新文本(“确定”),
已按下:(){
Navigator.of(context.pop();
},
)
],
);
}
);
}
}

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

而不是使用rethrow或引发新异常。返回一个Future.error()

Future methodThatErrorsOnCall(){
返回Future.error();
}
...
...
methodThatErrorsOnCall.catchError((e){
print('我想显示一个对话框:${e.error}');//回调激发。
return false;//Future以false完成
})

尝试
/
捕获
,但异步代码的异常仅在具有
异步
的函数中有效,否则您需要通过
onError
回调或在返回的
未来
上使用
捕获错误(…)
,这显然更难正确

  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');
      }
void onVerifyCodeBtnPressed(BuildContext上下文)async{//添加了async
if(_formKey.currentState.validate()){
字符串email=\u emailController.text;
字符串passwd=\u passwdController.text;
未来包络线;
试一试{
Envelope=await RemoteUserServices.loginUser(//添加了'await'`
电子邮件(passwd);
}论SocketException{
抛出异常(“Internet已关闭”);
}
  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');
      }