NestJS Exception Filter does not catch GraphQL validation exceptions/errors

342 Views Asked by At

I have a NestJS Exception filter. However, it does not catch any GQL exceptions. For example, if I leave out a required field in a GQL input, a BAD_INPUT or GRAPHQL_VALIDATION_FAILED exception error is sent back from the NestJS service to the client, but the Exception Filter is not called.

The exception filter is called for other service-related exceptions within the app, just not for GQL validation exceptions.

I have a feeling this might be because they are being thrown in the Apollo context before NestJS has a chance to wrap the context. If this is the case, then how can I catch GQL validation exceptions (to log them)?

@Catch()
export class CustomExceptionFilter implements ExceptionFilter {
  constructor(private readonly logger: Logger) {}  

  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();     
   
    this.logger.error(Exception occurred (logged from filter): ${exception}, exception.stack);   

    response.status(500).json({
      statusCode: 500,
      message: 'Internal Server Error',
    })
  }
}

EDIT - I used formatError instead which got the job done

 GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,        
      formatError: (error) => {
        // Errors thrown from the Apollo GQL context won't reach NestJS filters
        if (
          error.extensions &&
          error.extensions.code !== 'INTERNAL_SERVER_ERROR'
        ) {
         // log here 
        }
        return error
      },
1

There are 1 best solutions below

1
Uder Moreira On

The author response saved me.

EDIT - I used formatError instead which got the job done

GraphQLModule.forRoot({ driver: ApolloDriver,
formatError: (error) => { // Errors thrown from the Apollo GQL context won't reach NestJS filters if ( error.extensions && error.extensions.code !== 'INTERNAL_SERVER_ERROR' ) { // log here } return error },