Handling exception HTTP request flutter

Ray Coder

I want to handle http request flutter with some error message but I got so many error 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 returnresponse 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 it my app_exception.dart i got from stackoverflow and others 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 suggestion 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) { ^^^^^^^^^^^^^^^^

Ray

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

https://pub.dev/packages/dio

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related