Skip to content

Instantly share code, notes, and snippets.

@shakthizen
Last active June 10, 2024 16:09
Show Gist options
  • Save shakthizen/d644aaf19ca837a4a29a92ebad551055 to your computer and use it in GitHub Desktop.
Save shakthizen/d644aaf19ca837a4a29a92ebad551055 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