Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to catch errors with flutter grpc Interceptor #745

Open
VladislavYakonyuk opened this issue Nov 26, 2024 · 0 comments
Open

How to catch errors with flutter grpc Interceptor #745

VladislavYakonyuk opened this issue Nov 26, 2024 · 0 comments

Comments

@VladislavYakonyuk
Copy link

I am trying to handle the token error when it has expired and perform refreshToken. But my provider that receives network responses from the grpc client receives the response before the token is refreshed. I can see in devtools that the token has been refreshed and the request has been sent

class RefreshTokenInterceptors extends ClientInterceptor {
  final Ref ref;

  RefreshTokenInterceptors({required this.ref});

  @override
  ResponseFuture<R> interceptUnary<Q, R>(
    ClientMethod<Q, R> method,
    Q request,
    CallOptions options,
    invoker,
  ) {
    return super.interceptUnary(method, request, options, invoker)
      // ignore: discarded_futures
      ..catchError((e) async {
        final error = e as GrpcError;
        final currentToken =
            ref.read(storageProvider).getString(StorageKeys.accessToken);

        if (currentToken.isNotEmpty) {
          if (error.code == 7) {
            final res = await ref.read(authProvider.notifier).refreshToken();

            return res.fold(
              (l) => null,
              (r) async {
                if (r.accessToken.isNotEmpty) {
                  return invoker(
                    method,
                    request,
                    CallOptions(
                      providers: [
                        (Map<String, String> metadata, String uri) async {
                          try {
                            metadata["authorization"] = r.accessToken;
                          } catch (e) {
                            log("interceptor error ${e.toString()}");
                          }
                        }
                      ],
                    ),
                  );
                }
              },
            );
          }
        }
        throw e;
      });
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant