如何从“飞镖未来”中返回错误? [英] How do I return error from a Future in dart?

查看:77
本文介绍了如何从“飞镖未来”中返回错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的flutter应用程序中,我拥有一个处理http请求并返回解码数据的未来。但是如果状态代码!= 200 可以通过 .catchError()处理程序。

In my flutter app, I have a future that handles http requests and returns the decoded data. But I want to be able to send an error if the status code != 200 that can be gotten with the .catchError() handler.

在这里:

Future<List> getEvents(String customerID) async {
  var response = await http.get(
    Uri.encodeFull(...)
  );

  if (response.statusCode == 200){
    return jsonDecode(response.body);
  }else{
    // I want to return error here 
  }
}

,当我调用此函数时,我希望能够得到如下错误:

and when I call this function, I want to be able to get the error like:

getEvents(customerID)
.then(
  ...
).catchError(
  (error) => print(error)
);


推荐答案

您可以使用 throw

Future<List> getEvents(String customerID) async {
  var response = await http.get(
    Uri.encodeFull(...)
  );

  if (response.statusCode == 200){
    return jsonDecode(response.body);
  }else{
    // I want to return error here 
       throw("some arbitrary error"); // error thrown
  }
}

这篇关于如何从“飞镖未来”中返回错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆