CodingAleCR / http_interceptor

A lightweight, simple plugin that allows you to intercept request and response objects and modify them if desired.
MIT License
134 stars 67 forks source link

How do i catch socket exceptions #34

Closed patrickoramah closed 4 years ago

patrickoramah commented 4 years ago

I am trying to catch Socket exceptions in my service but it keeps slipping through and throwing the Exception block instead.

This is my implementation. Kindly advise

    try {
      http.Response response =
          await client.post('$baseUrl/auth/', body: login.toJson());
      Map<String, dynamic> data = jsonDecode(response.body);
      if (response.statusCode == 401) {
        throw Failure('Wrong username and password combination');
      }
      return data;
    } on HttpException catch (e) {
      throw Failure(e.toString());
    } on SocketException {
      throw Failure('No Internet connection πŸ˜‘');
    } on FormatException {
      throw Failure('Bad response format πŸ‘Ž');
    } on Exception {
      throw Failure('Unexpected error 😒');
    }
class HttpInterceptor implements InterceptorContract {
  @override
  Future<RequestData> interceptRequest({RequestData data}) async {
    if (data.headers.containsKey('requireAuth')) {
      String accessToken = await _storage.read(key: 'access');
      data.headers.remove('requireAuth');
      data.headers['Authorization'] = 'Bearer $accessToken';
      data.headers["Content-Type"] = "application/json";
    }
    print(data.body);
    return data;
  }

  @override
  Future<ResponseData> interceptResponse({ResponseData data}) async {
    print(data.body);
    return data;
  }
}

Client _client = HttpClientWithInterceptor.build(
  interceptors: [
    HttpInterceptor(),
  ],
  retryPolicy: ExpiredTokenRetryPolicy(),
);

Client get client => _client;

Also how do I set this up for the exceptions to be handled globally

issue-label-bot[bot] commented 4 years ago

Issue-Label Bot is automatically applying the label question to this issue, with a confidence of 0.75. Please mark this comment with :thumbsup: or :thumbsdown: to give our bot feedback!

Links: app homepage, dashboard and code for this bot.

CodingAleCR commented 4 years ago

Hi @patrickoramah The way you are attempting to catch the SocketException should be just fine, in this case the problem is related to the library; it seems like there's a bug with the current version, I am currently checking it out and fixing it soon. Thanks for opening an issue for this! πŸ‘‹πŸΌ

CodingAleCR commented 4 years ago

Hi, me again, fixed in #35 with the new release 0.3.2 πŸš€