如何在Android屏幕上显示来自HTTP请求的异常

时间:2020-10-03 06:02:24

标签: android flutter dart

我正在使用基于Flutter的基本get请求,该请求将发送到RESTful服务器。执行此请求的代码如下:

Future<List<Description>> getTheInfo() async {
    List<Description> result;

    try {
      http.Response resp = await http.get(theUrl + "/home/devices");

      if(resp.statusCode == 200) {
        var jsonstr = json.decode(resp.body);
        var list = jsonstr["devices"] as List;
        result = list.map<Description>((json) => Description.fromJson(json)).toList();
      }
      else {
        print('FAILURE: '+resp.statusCode.toString());
      }
    } catch(exe) {
       print('Socket Failure: '+exe.toString());
       throw CustomException("FAILURE: ",exe.toString());
    }

     return(result);
  }

自定义例外是我从下面的Internet上获取的:

class CustomException implements Exception {
  final _message;
  final _prefix;

  CustomException([this._message, this._prefix]);

  String toString() {
    return "$_prefix$_message";
  }
}

我的问题是,尽管我能够将开发环境中发生的任何故障打印到控制台,但我无法查看设备上发生的情况。我在手机上进行测试时发现失败,而在开发环境中却看不到。

我想做的事情是通过某种方式在模拟器(在开发环境中)和实际手机的屏幕上(当我创建APK进行测试时)显示GET请求引发的异常在我的设备上)。有什么方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

不确定在这里要完成什么,但是有一种优雅的方法可以在UI上显示故障和异常,以使用户知道。在生产应用中,这也是一个好习惯。

您需要的是dartz,dartz是一个功能强大的程序包。

使用dartz,您可以使用Either类型返回Future<List<Description>>CustomException

这就是它如何适合您的代码。


Future<Either<CustomException,List<Description>>>  getTheInfo() async {
    List<Description> result;

    try {
      http.Response resp = await http.get(theUrl + "/home/devices");

      if(resp.statusCode == 200) {
        var jsonstr = json.decode(resp.body);
        var list = jsonstr["devices"] as List;
        result = list.map<Description>((json) => Description.fromJson(json)).toList();

        return right(result); 
      }
      else {
        print('FAILURE: '+resp.statusCode.toString());
        
       return  left(CustomException("FAILURE: ",exe.toString()));
      }
    } catch(exe) {
       print('Socket Failure: '+exe.toString());

     return  left(CustomException("FAILURE: ",exe.toString()));
    }
  }

在用户界面方面,

...

   Widget build(BuildContext context) {

       FutureBuilder(
         future: getTheInfo(),
         builder: (_, AysncSnapshot snapshot) {
          if(snapshot.connectionState ==ConnectionStatet.waiting){
               return CircularProgressIndicator();
          }
           
        snapshot.data.fold( 
          (l)=> Center(child: Text(l.message),  // CustomException message 
       ),
        (r)=>  Center(child: Text("Success"),  // r contains the List<Description>
     );    
    }
  }
...

根据成功或失败,您可以渲染适当的小部件。

编辑: 这应该可以,但是如果不是BLoc,强烈建议切换到提供商或riverpord