0

我正在尝试创建一个登录表单,我试图在服务器未运行、无效凭据和未连接互联网时显示弹出对话框。这是我的代码。

 var data={};
  Future login() async {
    Dio dio = new Dio();
    
    try {  
      data = {
        'username':user.username,
        'password':user.password,
        'date': formattedDate
      }; 
     await dio
          .post(localhostUrlLogin, data: json.encode(data),)
          .then((onResponse) async {
            Navigator.push(
              context, new MaterialPageRoute(builder: (context) => Navigation()));
         });
    } catch (e) {
      
      print(OSError.noErrorCode);
      if (OSError.noErrorCode== -1) {
         showDialog(
            context: context,
            builder: (BuildContext context) {
              return AdvanceCustomAlert(
                title: "Connection Error",
                descriptions: "Connection error",
                icon: Icons.error,
                bgcolor: Colors.red,
                fgcolor: Colors.red,
              );
            });
        
      } else {
        
        print("con er");
        showDialog(
            context: context,
            builder: (BuildContext context) {
              return AdvanceCustomAlert(
                title: "Try Again",
                descriptions: "Invalid username or password!",
                icon: Icons.error,
                bgcolor: Colors.red,
                fgcolor: Colors.red,
              );
            });
       
      }
    }
  }

OSError.noErrorCode在所有情况下都得到-1,我在后端(api)上传递了无效的输入错误,但在尝试代码之后我无法访问onResponse。

请让我知道我该怎么做。

4

1 回答 1

0

您可以按以下方式正确处理 dio 错误

try {
      Response response = await allDataRepository.getData();
      print(response.toString());

    } on DioError catch (dioError) {
      print(dioError);
      if (dioError.type == DioErrorType.response) {
        switch (dioError.response!.statusCode) {
          case 404:
            log(error: '400 - Not found');
            break;
          case 401:
            log(error: '401 - Unauthorized.');
            break;
          case 500:
            log(error: '500 - Internal Server Error.');
            break;
          case 501:
            log(error: '501 - Not Implemented Server Error.');
            break;
          case 502:
            log(error: '502 - Bad Gateway Server Error.');
            break;
          default:
            log(error: '${dioError.response!.statusCode} - Something went wrong while trying to connect with the server');
            break;
        }
      } else if (dioError.type == DioErrorType.other) {
        log(error: 'Please check your internet connection. Try again switching to a different connection');
      }
    } catch (e) {
      log(error: 'Something went wrong : $e');
    }

存储库应如下所示(data_repository.dart)

class DataRepository {
  final HttpClient httpClient;

  DataRepository({required this.httpClient});

  Future<Response> getData() async {
    Response response = await httpClient.dio.get(
      GlobalConfig.getDataUrl,
    );

    return response;
  }
}

HttpClient 应该看起来像这样 (http_client.dart)

class HttpClient {
  final Dio dio;

  HttpClient({required this.dio});

  static final String basePath = GlobalConfig.baseUrl;

  void addBasePathInterceptor() {
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
        print(options.uri);
        if (!options.path.startsWith("http")) {
          options.baseUrl = basePath;
        }

        return handler.next(options);
      },
    ));

    addUrlInterceptor();
    // addVersionInterceptor();
  }

  Interceptor? sessionCookieInterceptor;
  Interceptor? versionCookieInterceptor;
  Interceptor? status401Interceptor;

  // void addSessionCookieInterceptor(List<String> cookies) {
  //   sessionCookieInterceptor = InterceptorsWrapper(
  //       onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
  //     options.headers['cookie'] = cookies.join(';');
  //   });

  //   dio.interceptors.add(sessionCookieInterceptor!);
  // }

  // void addVersionInterceptor() {
  //   versionCookieInterceptor = InterceptorsWrapper(
  //       onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
  //     options.headers['website-version'] = '26.3.0';
  //   });

  //   dio.interceptors.add(versionCookieInterceptor!);
  // }

  void addUrlInterceptor() {
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
        print('onRequest ${options.uri}');
        return handler.next(options);
      },
      onResponse: (Response response, ResponseInterceptorHandler handler) {
        print('onResponse ${response.statusCode} ${response.realUri}');
        return handler.next(response);
      },
      onError: (DioError error, ErrorInterceptorHandler handler) {
        if (error.type == DioErrorType.response) {
          print('------------------------');
          print(error.error);
          print(error.response?.realUri);
          print(error.response?.statusCode);
          print(error.response?.data);
          print('------------------------');
        }

        return handler.next(error);
      },
    ));
  }

  void add401Interceptor() {
    print("Adding 401 interceptor");
    status401Interceptor = InterceptorsWrapper(
        onError: (DioError res, ErrorInterceptorHandler handler) {
      if (res.response != null && res.response?.statusCode == 401) {
        // globalBloc.add(ShowErrorSnackBar(
        //     error: 'You have been logged out, Please login again'));
        // authenticationBloc.add(AuthenticationUnauthenticatedEvent());
        // mainBloc.add(LougoutEvent());
      }
      return handler.next(res);
    });
    dio.interceptors.add(status401Interceptor!);
  }

  // void remove401Interceptor() {
  //   dio.interceptors.remove(status401Interceptor);
  // }
}

最后,在 main.dart 中初始化 HttpClient 如下

void main() async {

  // Intializing Http Client
  HttpClient(dio: sl()).addBasePathInterceptor();

  runApp(MyApp());
}

请注意,您只需要以下一堆代码。但我已经描述了一种处理应用程序中每个 API 调用的好方法。

Dio dio = new Dio();
try {
      Response response = await dio.get(GlobalConfig.getDataUrl);
      print(response.toString());

    } on DioError catch (dioError) {
      print(dioError);
      if (dioError.type == DioErrorType.response) {
        switch (dioError.response!.statusCode) {
          case 404:
            log(error: '400 - Not found');
            break;
          case 401:
            log(error: '401 - Unauthorized.');
            break;
          case 500:
            log(error: '500 - Internal Server Error.');
            break;
          case 501:
            log(error: '501 - Not Implemented Server Error.');
            break;
          case 502:
            log(error: '502 - Bad Gateway Server Error.');
            break;
          default:
            log(error: '${dioError.response!.statusCode} - Something went wrong while trying to connect with the server');
            break;
        }
      } else if (dioError.type == DioErrorType.other) {
        log(error: 'Please check your internet connection. Try again switching to a different connection');
      }
    } catch (e) {
      log(error: 'Something went wrong : $e');
    }
于 2021-08-26T13:30:45.367 回答