How to handle timeout error with Dio in Flutter?
Asked Answered
M

4

21

I'm using Dio to handle APIs functions.

Here's my code:

  Future<List<ItemModel>> getItems() async {
    try {
      Response response = await dio.get("$_apiUrl$_itemEndPoint",
          options: Options(headers: {
            "Accept": 'application/json',
          }));

      List<ItemModel> _items = List<ItemModel>();

      response.data['data']?.forEach((c) {
        _items.add(ItemModel.fromMap(c));
      });
      return _items;
    } catch (e) {
      throw (e);
    }
  }

How can I catch an error based on timeout of send and receive?

Mayer answered 16/1, 2020 at 12:40 Comment(0)
A
32

Manage timeout exception using dio :

ApiRepositary.dart

 class ApiRepositary {
  Dio dio;

  ApiRepositary() {
    if (dio == null) {
      BaseOptions options = new BaseOptions(
          baseUrl: "your base url",
          receiveDataWhenStatusError: true,
          connectTimeout: 60*1000, // 60 seconds
          receiveTimeout: 60*1000 // 60 seconds
          );

      dio = new Dio(options);
    }
  }

  Future<LoginResponse> getLoginDetails(var loginRequestData) async {
    try {
      Response response = await dio.post("/authenticate", data: loginRequestData);
      final LoginResponse loginResponse = LoginResponse.fromJson(response.data);
      return loginResponse;
    }on DioError  catch (ex) {
      if(ex.type == DioErrorType.CONNECT_TIMEOUT){
        throw Exception("Connection  Timeout Exception");
      }
      throw Exception(ex.message);
    }
  }

}

Example of handle exception :

void checkLogin(){
 LoginRequest loginRequest = new LoginRequest(
            email: "[email protected]",password: "passs@123");

        var requestBody =jsonEncode(loginRequest);
        debugPrint("Request Data : $requestBody");

        _apiRepositary.getLoginDetails(requestBody).then((response){
          debugPrint("Login Success $response");
          //manage your response here 

        },
          onError: (exception){
              //Handle exception message
            if(exception.message != null ){

              debugPrint(exception.message); // Here you get : "Connection  Timeout Exception"

            }
          },
        );
}
Amberly answered 19/1, 2020 at 6:38 Comment(2)
mate, what does the receiveDataWhenStatusError do on dio options? I read the docs and still doesn't understand what it does.Freewheel
Hi @Flux, Here you get errorBody response exception.message.error Here exception is dioException.Amberly
A
8

You to define DIO option first:

 BaseOptions options = new BaseOptions(
  baseUrl: "http://example.org",
  connectTimeout: 5000,
  receiveTimeout: 3000,
);

then:

Dio dio = new Dio(options);

var jsonNews = await dio.get(
        'http://example.org/v2/everything?q=bitcoin&from=2020-01-24&sortBy=publishedAt&apiKey=7f3c604b6e2245c88se50lzx02dc9cac1e2');

Source :

https://pub.dev/packages/dio

Applicative answered 24/2, 2020 at 22:15 Comment(1)
This is what I needed. I left out the receiveTimeout property though, as it was timing out download of the file even when the download was occurring successfully.Hobo
S
6

Here's what I'm guessing by looking at one of their test files and their error class:

try {
  await Dio().get("https://does.not.exist");
} on DioError catch (e) {
  if (e.type == DioErrorType.connectTimeout) {
    // ...
  }
  if (e.type == DioErrorType.receiveTimeout) {
    // ...
  }
}

Scalage answered 16/1, 2020 at 13:3 Comment(0)
Q
0

you can use the try-catch for Timeout exception and the handle it on you basis

Quadrant answered 16/1, 2020 at 13:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.