Search code examples
javascriptnode.jstypescriptnestjstypeorm

How can I handle TypeORM error in NestJS?


I'd like to create a custom exception filter that handles different kinds of TypeORM errors. I've looked up the TypeORM error classes, and it seems like there's no such thing in TypeORM like MongoError.

I wanted to make something similar to 1FpGLLjZSZMx6k's answer, and here's what I've done so far.

import { QueryFailedError } from 'typeorm';

@Catch(QueryFailedError)
export class QueryFailedExceptionFilter implements ExceptionFilter {
  catch(exception: QueryFailedError, host: ArgumentsHost) {
    const context = host.switchToHttp();
    const response = context.getResponse<Response>();
    const request = context.getRequest<Request>();
    const { url } = request;
    const { name } = exception;
    const errorResponse = {
      path: url,
      timestamp: new Date().toISOString(),
      message: name,
    };

    response.status(HttpStatus.BAD_REQUEST).json(errorResponse);
  }
}

If I need to catch another error for instance, EntityNotFoundError, I have to write the same code which is a very cumbersome task to do it.

It would be nice if I could handle errors by a single filter like below. Any ideas?

@Catch(TypeORMError)
export class EntityNotFoundExceptionFilter implements ExceptionFilter {
  catch(exception: MongoError, host: ArgumentsHost) {
    switch (exception.code) {
      case some error code:
        // handle error
    }
  }
}

Solution

  • In the documentation, it says:

    The @Catch() decorator may take a single parameter, or a comma-separated list. This lets you set up the filter for several types of exceptions at once.

    So in your case you could write:

    @Catch(QueryFailedError, EntityNotFoundError)