net不存在时如何处理套接字异常?

Kee*_*ani 2 asynchronous exception-handling flutter

如果没有网络,我想显示一个错误屏幕。我没有使用连接包,因为我不想连续检查。我只想在调用后端 api 并显示屏幕时处理异常。我无法捕获异常。

我发现了这个问题和这个关于套接字异常的问题,但似乎没有一个对我有帮助。

这就是我调用后端 api 的方式 -

callBackendApi() async {
  try {
    http.Response response = await Future.value(/*api call here*/)
        .timeout(Duration(seconds: 90), onTimeout: () {
      print('TIME OUT HAPPENED');
    });
  } catch (exception) {
    Fluttertoast.showToast(msg: 'Check internet connection.');
    print('Error occurred' + exception.toString());
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

我的解决方案是导入 'dart.io' 以便从 try 块中捕获 SocketException:

import 'package:http/http.dart' as http;
import 'dart:io';

try{

//Handle you network call code block in here

}on SocketException catch(_){

//To handle Socket Exception in case network connection is not available during initiating your network call

}
Run Code Online (Sandbox Code Playgroud)


JOh*_*hn 6

我像这样使用dio

try {

    var formData = FormData.from(Map<String, dynamic>.from(data));

    var response = await dio.post(
      uri,
      data: formData,
    );
    jsonResponse = json.decode(response.data);
  } on DioError catch (e) {

    if (DioErrorType.RECEIVE_TIMEOUT == e.type ||
        DioErrorType.CONNECT_TIMEOUT == e.type) {
      throw CommunicationTimeoutException(
          "Server is not reachable. Please verify your internet connection and try again");
    } else if (DioErrorType.RESPONSE == e.type) {
      // 4xx 5xx response
      // throw exception...
    } else if (DioErrorType.DEFAULT == e.type) {
         if (e.message.contains('SocketException')) {
           throw CommunicationTimeoutException('blabla');
         }
    } else {
          throw CommunicationException("Problem connecting to the server. Please try again.");
    }
 }
Run Code Online (Sandbox Code Playgroud)