Ray Coder
Ray Coder

Reputation: 1111

Handling exception HTTP request flutter

I want to handle http request flutter with some error message but I got so many errors here. I just make it based on the suggestion but it didn't work for me. Please, anyone, help me Here is my function to call API

getData(data, apiUrl) async {
    var tempUrl = _url + apiUrl + await _getToken();
    Uri uri = Uri.parse(tempUrl);
    var fullUrl = uri.replace(queryParameters: data);
    var res;
    try {
      var response = await http.get(fullUrl, headers: _setHeaders()).timeout(
          const Duration(seconds: 60));
      print(response.statusCode);
      if (response.statusCode != 200) {
        res = {
          "success": false,
          "status": response.statusCode,
          "message": _returnResponse(response)
        };
      }
      else {
        res = response;
      }
    }
    on SocketException {
      throw FetchDataException('No Internet connection');
    }
    on TimeoutException catch (e) {
      res = {
        "success": false,
        "status": response.statusCode,
        "message": "Connection timeout"
      };
    } on Error catch (e) {
      print('Error: $e');
    }

    return res;
  }

This is my return response for the others except 200

dynamic _returnResponse(http.Response response) {
    switch (response.statusCode) {
      case 400:
        throw BadRequestException(response.body.toString());
      case 401:
      case 403:
        throw UnauthorisedException(response.body.toString());
      case 500:
      default:
        throw FetchDataException(
            'Error occured while Communication with Server with StatusCode : ${response
                .statusCode}');
    }
  }

and here is my app_exception.dart I got from StackOverflow and other forums

class AppException implements Exception {
  final _message;
  final _prefix;

  AppException([this._message, this._prefix]);

  String toString() {
    return "$_prefix$_message";
  }
}

class FetchDataException extends AppException {
  FetchDataException([String message])
      : super(message, "Error During Communication: ");
}

class BadRequestException extends AppException {
  BadRequestException([message]) : super(message, "Invalid Request: ");
}

class UnauthorisedException extends AppException {
  UnauthorisedException([message]) : super(message, "Unauthorised: ");
}

class InvalidInputException extends AppException {
  InvalidInputException([String message]) : super(message, "Invalid Input: ");
}

I have tried so many suggestions but it didn't work at all

I got this error

Error: 'SocketException' isn't a type. on SocketException { ^^^^^^^^^^^^^^^

Error: 'TimeoutException' isn't a type. on TimeoutException catch (e) { ^^^^^^^^^^^^^^^^

Upvotes: 18

Views: 74308

Answers (2)

poppinjay13
poppinjay13

Reputation: 18

If the error occurring is on SocketException and Timeout exception ensure you have imported both dart.io and dart.async respectively in that file. As pertains to you code I was able to successfully run it but you can refer to the answer by Paresh Mangukiya for a step by step or refer here for more clarification on how to handle Network calls and exceptions with custom error responses in flutter.

Upvotes: 0

Ray
Ray

Reputation: 414

I used dio package. That's more easier and bug-less than i make it

https://pub.dev/packages/dio

Upvotes: 3

Related Questions