flutter异步请求数据,抛出异常灰屏问题

2022-06-16  本文已影响0人  道翼

项目需要,自定义data返回的数据code为500,500接收到要有弹窗提示

异步请求数据时,出现弹窗出现,但灰屏现象,报错位置猜测为弹窗和抛出异常

try {
      if(response.data.data['code'] == '500'){
        throw new Exception('这是一个异常');
      }
      return response.data;
} catch (e, r) {
      EasyLoading.showError(e.toString());
      LogUtil.error('网络请求错误:  错误信息-${e.toString()}');
      throw e;
}

修改后

try {
      if(response.data.data['code'] == '500'){
        // throw StateError('数据错误!');
        await Future.delayed(Duration(seconds: 1)).then(
                (e) => throw StateError('这是一个异常'));
      }
      return response.data;
} catch (e, r) {
      EasyLoading.showError(e.toString());
      LogUtil.error('网络请求错误:  错误信息-${e.toString()}');
      // throw e;
      return Future.error('解析响应数据异常2');
}

修改原因是这是异步请求,try、catch里面的写法是异步变为同步后捕获

链接:flutter异常处理

上一篇 下一篇

猜你喜欢

热点阅读