如何捕获http.get(SocketException)

时间:2019-08-26 00:20:34

标签: flutter dart

我是Flutter&Dart的新手,正试图完成我的第一个应用程序。

我无法捕获(带有try-catch块)http.get SocketException(在您调用API并关闭WiFi时发生)

我没有运气就尝试了Internet上的所有内容,甚至尝试了(Dio)软件包来捕获此异常,但没有成功。

如何重现:使用底层代码...关闭手机的WiFi ...调用API ...现在该应用程序在IDE中崩溃,并显示(SocketException)。

图片:https://imgur.com/bA0rKEN

这是我的简单代码(已更新)

     RaisedButton(
              child: Text("Call API"),
              onPressed: () async {
                try {
                  http.Response response = await getLoginResponse();
                  //do something with response
                  print(response.body);
                } catch (e) {
                  print("Button onPressed Error: " + e.toString());
                }
              },
            )
//---------------------------------------------------------------
Future<http.Response> getLoginResponse() {
    return http.get(loginUrl).timeout(Duration(seconds: 10))
    .then((response) {
      return response;
    }, onError: (e) {
      print("onError: " + e.toString());
    }).catchError((err) {
      print("catchError: " + err.toString());
      return null;
    });
  }

2 个答案:

答案 0 :(得分:0)

如果要在RaisedButton的try-catch块中捕获,而不是在getLoginInfo()方法中返回null,则必须返回这样的Exception:

 Future<List<LoginObject>> getLoginInfo() async {
    try {
      List<LoginObject> loginObjectList = List<LoginObject>();
      http.Response loginResponse =
          await http.get(loginUrl).timeout(Duration(seconds: 10));
      if (loginResponse.statusCode == 200) {
        loginObjectList = loginObjectFromJson(loginResponse.body);
        return loginObjectList;
      } else {
        throw Exception('Authentication Error');
      }
    } catch (e) {
      print("Error: " + e.toString());
      return throw Exception('Connection Error');;
    }
  }

注意:如果要处理每个错误响应,都可以创建一个自定义ErrorModelClass并使用它处理错误状态,最后返回ErrorModelClass。

 catch (error) {
      print(error);
      throw error is HttpResponseError ? error : HttpResponseError(0,"error connection");

HttpResponseError 是我的自定义模型类。

答案 1 :(得分:0)

您可以捕获多种类型的错误并分别处理每个错误

示例:

import 'dart:io' as Io;

http.Client client = http.Client();

try {
  response = await client.get(url).timeout(new Duration(seconds: 10));
} on Io.SocketException catch (_) {
  throw Exception('Not connected. Failed to load data');
} on TimeoutException catch (_) {
  throw Exception('Not connected. TimeOut Exception');
} catch (e) {
  // Default error handling;
}