Skip to content

Instantly share code, notes, and snippets.

@MaherSaif
Forked from shakthizen/dio_exception.md
Created October 30, 2024 06:19
Show Gist options
  • Save MaherSaif/200efe24600816526f2834f3991e7645 to your computer and use it in GitHub Desktop.
Save MaherSaif/200efe24600816526f2834f3991e7645 to your computer and use it in GitHub Desktop.
Unable to catch Flutter Dio exception

I found a hacky solution. We are overriding all the exceptions thrown by default. Then we are going to create custom interceptor to handle and throw exceptions. This way we can catch the DioException as we did before.

  1. Create a base client like this. You have to set validateStatus function to return true whatever the status code is.
final baseOptions = BaseOptions(
  baseUrl: host,
  contentType: Headers.jsonContentType,
  validateStatus: (int? status) {
    return status != null;
    // return status != null && status >= 200 && status < 300;
  },
);

final dio = Dio(baseOptions);
  1. Create a custom interceptor to raise exceptions
class ErrorInterceptor extends Interceptor {
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    final status = response.statusCode;
    final isValid = status != null && status >= 200 && status < 300;
    if (!isValid) {
      throw DioException.badResponse(
        statusCode: status!,
        requestOptions: response.requestOptions,
        response: response,
      );
    }
    super.onResponse(response, handler);
  }
}
  1. Add that to the Dio interceptors list
dio.interceptors.addAll([
    ErrorInterceptor(),
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment