0
votes

I am playing around with NestJS and I would like to take the error thrown from TypeORM and convert it into a shape that I can control.

Right now, I'm just trying to catch the error thrown from TypeORM and log it out to see that my custom filter is working correctly. But unfortunately, my console.log statement in the filter is never logging.

Here is a slimmed down version of my service and filter

user.service.ts

export class UserService {
  constructor(
    @InjectRepository(Users)
    private readonly userRepository: Repository<Users>,
  ) {}

  @UseFilters(new TypeOrmFilter())
  async create(createUserDto: CreateUserDto) {
    const user = this.userRepository.create(createUserDto);
    return this.userRepository.save(user);
  }
}

type-orm-filter.ts

@Catch()
export class TypeOrmFilter implements ExceptionFilter {
  catch(exception: Error, host: ArgumentsHost) {
    console.log('\nI have caught an error\n', exception);
    throw exception;
  }
}

Here is the log output from the error being thrown by TypeORM

[Nest] 61496   - 04/11/2021, 9:01:42 PM   [ExceptionsHandler] invalid input syntax for type uuid: "123e4567" +2482ms
QueryFailedError: invalid input syntax for type uuid: "123e4567"
    at new QueryFailedError (my-nest-project/error-project-nestjs/node_modules/typeorm/error/QueryFailedError.js:11:28)
    at PostgresQueryRunner.<anonymous> (my-nest-project/error-project-nestjs/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:247:31)
    at step (my-nest-project/error-project-nestjs/node_modules/typeorm/node_modules/tslib/tslib.js:141:27)
    at Object.throw (my-nest-project/error-project-nestjs/node_modules/typeorm/node_modules/tslib/tslib.js:122:57)
    at rejected (my-nest-project/error-project-nestjs/node_modules/typeorm/node_modules/tslib/tslib.js:113:69)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
1
what if you use pipes instead? like docs.nestjs.com/interceptors#exception-mapping it will map a typeorm error to another oneMicael Levi

1 Answers

0
votes

You missed the await in UserService#create :p

tip: If you configure ESLint properly, this might never happen again because you already marked that method with await (https://eslint.org/docs/rules/require-await). Or just enforce typing the return (https://github.com/typescript-eslint/typescript-eslint/blob/v3.10.1/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md)