Is it possible to override the DEFAULT_TEARDOWN function inside exceptions-zone.ts?

Viewed 289

I'm trying to create an application with NestJS framework and I'd like to check if a specific Service is in the application context but, the framework default behavior is exiting the process when it doesn't find the Service inside the context.

I've surrounded the get method with try...catch but it doesn't work because of the process.exit(1) execution.

private async loadConfigService(server: INestApplication): Promise<void> {
    try {
      this.configService = await server.get<ConfigService>(ConfigService, { strict: false });
    } catch (error) {
      this.logger.debug('Server does not have a config module loaded. Loading defaults...');
    }
    this.port = this.configService ? this.configService.port : DEFAULT_PORT;
    this.environment = this.configService ? this.configService.environment : Environment[process.env.NODE_ENV] || Environment.DEVELOPMENT;
    this.isProduction = this.configService ? this.configService.isProduction : false;
  }

I'd like to catch the exception to manage the result instead of exiting the process.

2 Answers

Here's what I came up with:

import { NestFactory } from '@nestjs/core';

export class CustomNestFactory {
  constructor() {}

  public static create(module, serverOrOptions, options) {
    const ob = NestFactory as any;
    ob.__proto__.createExceptionZone = (receiver, prop) => {
      return (...args) => {
        const result = receiver[prop](...args);
        return result;
      };
    };
    return NestFactory.create(module, serverOrOptions, options);
  }
}

Now, instead of using the default NestFactory I can use my CustomNestFactory

Dirty, but it works

Here is my code to solve same issue:

import { ExceptiinsZone } from '@nestjs/core/errors/exceptions-zone';

ExceptionsZone.run = callback => {
  try {
    callback();
  } catch (e) {
    ExceptionsZone.exceptionHandler.handle(e);
    throw e;
  }
};

You may need to override asyncRun() also for other method.

Related