How can I make a NestJS GraphQL request bypass the built-in exception filter and only use the global exception filter for error handling?

422 views Asked by At

I'm currently working with NestJS and GraphQL, and I'm trying to handle all errors using a custom global exception filter that I've created. However, I've noticed that the built-in exception filter always handles and logs the errors before my custom filter gets a chance to do so.

I find this behavior quite puzzling, especially when dealing with errors that occur during a GraphQL request. I've tested this with a simple HTTP request and found that the global exception filter handles all errors as expected, without triggering the built-in exception filter.

So, my question is: How can I configure my application to only trigger my custom global filter and bypass the built-in exception filter when handling errors?

Here's a snippet of my code for reference:

foo-resolver.ts FooResolver:

import { Query, Resolver } from "@nestjs/graphql";
import { ApolloError } from "apollo-server-express";

@Resolver()
export class FooResolver {
  @Query(() => String)
  error(): string {
    throw new ApolloError('throw Error');
    return 'Hello World!';
  }
}

global-exception.filter.ts:

import { ArgumentsHost, Catch, Logger } from "@nestjs/common";
import { GqlArgumentsHost, GqlContextType, GqlExceptionFilter } from "@nestjs/graphql";

@Catch()
export class GlobalExceptionFilter implements GqlExceptionFilter {
  private logger = new Logger(this.constructor.name);

  catch(exception: any, host: ArgumentsHost): void {
    if (host.getType() === 'http') {
      // do something that is only important in the context of regular HTTP requests (REST)
      const ctx = host.switchToHttp();
    } else if (host.getType<GqlContextType>() === 'graphql') {
      const gqlHost = GqlArgumentsHost.create(host);
    }
  }
}

main.ts

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new GlobalExceptionFilter());
  await app.listen(3000);
}
bootstrap();

I hope this makes my question clear. Any help would be greatly appreciated. Thank you in advance!

I tried to handle all errors in my NestJS application using a custom global exception filter. I expected that all errors, including those from GraphQL requests, would be handled by this filter. However, I found that the built-in exception filter is still handling and logging the errors before my custom filter gets a chance to do so.

0

There are 0 answers