Baterka
Baterka

Reputation: 3714

How to catch NestJS exceptions thrown in `forFeature` or `forRoot`?

I setuped configuration validation as described in documentation of NestJS: https://docs.nestjs.com/techniques/configuration#schema-validation

Validation works as expected, but when my .env file is not valid, I am getting plain error, for example:

Error: Config validation error: "FOO_BAR" is required at Function.forRoot (<PATH>\@nestjs\config\dist\config.module.js:44:27)

This error is not thrown by Nest so approach with globalFilter what can catch every Nest error not work: https://docs.nestjs.com/websockets/exception-filters#exception-filters

How to catch this error to be able to format it?

EDIT: This is more general question: How to catch errors thrown inside forRoot, forFeature in NestJS?

Upvotes: 2

Views: 970

Answers (1)

Doan Thai
Doan Thai

Reputation: 685

This is impossible. Because NestJS catch every errors and handle it when module init except function such as onModuleInit. Error that you see from terminal actually just like console.log. This is file handle and show log error when module init ExceptionHandler.

import { RuntimeException } from './exceptions/runtime.exception';
import { Logger } from '@nestjs/common/services/logger.service';

export class ExceptionHandler {
  private static readonly logger = new Logger(ExceptionHandler.name);

  public handle(exception: RuntimeException | Error) {
    if (!(exception instanceof RuntimeException)) {
      ExceptionHandler.logger.error(exception.message, exception.stack);
      return;
    }
    ExceptionHandler.logger.error(exception.what(), exception.stack);
  }
}

It isn't extend from Error and don't rethrow new Exception.

So, you can't catch error inside forRoot or forFeature. but as you see because it is logging, so you can overwrite logger in Nestjs, catch error message that you need format. This way may be a little stupid.

...
import { LoggerService, LogLevel } from '@nestjs/common/services/logger.service';
// Add custom logger
class CLogger implements LoggerService {
  log(message: any, ...optionalParams: any[]) {
    console.log(message);
  }
  error(message: any, ...optionalParams: any[]) {
    // check condition error at here
    console.error(message);
  }
  warn(message: any, ...optionalParams: any[]) {
    console.warn(message);
  }
  debug?(message: any, ...optionalParams: any[]) {
    console.debug(message);
  }
  verbose?(message: any, ...optionalParams: any[]) {
    console.debug(message);
  }
  fatal?(message: any, ...optionalParams: any[]) {
    console.debug(message);
  }
  setLogLevels?(levels: LogLevel[]) {
    // console.debug(message);
  }
}
// Import custom logger to NestJs at startup
...
    let app = await NestFactory.create(AppModule, {
      logger: new CLogger(),
    });
...

Upvotes: 0

Related Questions