Flutter-如何从飞镖期货中返回错误?

时间:2019-02-01 07:19:25

标签: promise dart flutter future

在我的flutter应用程序中,我拥有一个处理http请求并返回解码数据的未来。但是我希望能够通过.catchError()处理程序获取状态代码!= 200时发送错误。

在这里:

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 
  }
}

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

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

2 个答案:

答案 0 :(得分:11)

如果您想在return中捕获错误,请使用catchError()

如果您想在throw中捕获错误,请使用try/catch

return Future.error("This is the error", StackTrace.fromString("This is its trace"));

答案 1 :(得分:4)

您可以使用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
  }
}