'intercepting angular apollo requests and handling errors globally without links?

I've been trying to log the user off when hitting a 401 for whatever reason, I do need access to angular services such as the router and application specific services for the checks I'm doing, from the examples I've seen online, if I'm using links, I don't have access to these Angular injectables.

I have created an interceptor to catch HTTP requests globally and while it does intercept the initial HTTP request made to the graphql backend, when the graphql request fails, the interceptor does not catch it and actions are not fired.

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    protected accountService!: AccountService;

    constructor(private inj: Injector, private router: Router) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.accountService = this.inj.get<AccountService>(AccountService);

        return next.handle(request.clone({ withCredentials: true })).pipe(
            catchError((err) => {
                if (err?.status === 401) {
                    localStorage.clear();
                    this.router.navigate(['']);
                }
                return throwError(() => err);
            }),
        );
    }
}

If however I'm adding a catchError() in the pipe of the individual apollo call, it does get caught, but I don't want to be adding a ton of boilerplate code in every graphql request, that's what interceptors are for.

 return this.apollo
            .query<any>({
                query: GET_CHECKOUTS,
                variables: params,
            })
            .pipe(
                map((response: ApolloQueryResult<any>) => {
                    const totalCount = response.data.getCheckouts.totalCount;
                    const list: Order[] = response.data.getCheckouts.data;
                    return { totalCount: totalCount, data: list };
                }),
                catchError((err) => {
                    console.log('ERRR IN APOLLO REQUEST CAUGHT');
                    return throwError(() => err);
                }),
            );

What's the correct pattern in this scenario?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source