【问题标题】:Error: DioError [DioErrorType.other]: SocketException: Failed host lookup: not being caught错误:DioError [DioErrorType.other]:SocketException:主机查找失败:未被捕获
【发布时间】:2022-01-23 20:54:51
【问题描述】:

我正在使用 dio 4.0.2。问题是当没有互联网连接时(没有打开互联网和 wifi 时),SocketException: Failed host lookup 没有被捕获。我通过拦截器的 onError 方法进行了检查,我确信它正在从拦截器发送错误。但是发布请求不会为此引发错误。

这是我的错误代码拦截器:

@override
 void onError(DioError err, ErrorInterceptorHandler handler) {
    super.onError(err, handler);
 }

我怎样才能捕捉到这个?

【问题讨论】:

    标签: flutter dio


    【解决方案1】:

    不知道为什么,但这对我有用:

      // add error interceptor to catch all errors
        dioBuilder.dio.interceptors.add(
          InterceptorsWrapper(
            onError: (error, handler) {
              // Do stuff here
              handler.reject(error); // Added this line to let error propagate outside the interceptor
            },
          ),
        );
    

    【讨论】:

      【解决方案2】:

      我是这样使用的:

      bool _isServerDown(DioError error) {
        return (error.error is SocketException) || (error.type == DioErrorType.connectTimeout);
        }
      
      
       @override
        Future<void> onError(DioError error, ErrorInterceptorHandler handler) async {
          if (_isServerDown(error)) {
            Response? response;
            try {
              response = await tryAnotherUrl(error.requestOptions);
            } catch (error) {
              if (error is DioError) {
                response = error.response;
                handler.next(error);
                return;
              }
            }
            if (response != null) {
              handler.resolve(response);
            } else {
              handler.next(error);
            }
            return;
          }
      

      【讨论】:

        猜你喜欢
        • 2021-03-06
        • 2023-03-13
        • 2021-04-19
        • 2021-08-31
        • 1970-01-01
        • 2013-07-07
        • 2019-07-12
        • 2021-05-09
        • 2020-03-08
        相关资源
        最近更新 更多