Nest: Nest should not swallow exceptions in NestFactoryStatic.initialize

Created on 29 Jul 2020  路  10Comments  路  Source: nestjs/nest

If an exception is thrown in:

https://github.com/nestjs/nest/blob/f0e7597635b3abdc5f6cae7667a60070a667dbca/packages/core/nest-factory.ts#L159-L168

I don't think there is a way to capture it outside of nest.

Expected behavior

I would expect the exception to bubble up so I can capture it. For example, I'd like to send it to Sentry.

core type

Most helpful comment

Sounds good @kamilmysliwiec. @larose @kamilmysliwiec I would like to create a pr for this, if you allow me.

All 10 comments

Can you please share a minimal repository that shows what you want to accomplish and why this snippet of code is a blocker for you?

Thanks @kamilmysliwiec, I've created a minimal repository: https://github.com/larose/nest-error-swallow-on-init.

It's not a blocker per say as there are ways to detect failures during Nest initialization outside of the process, but this is not convenient. In my case, my Sentry dashboard will show no errors, even though my Nest app doesn't start.

Nest should not catch all errors, but let them bubble up instead so the client code can decide what to do with them.

@kamilmysliwiec, I see that this issue still has the "needs clarification" label. Did my comment above clarified things?

I think we should add an option named abortOnError that could be disabled on-demand to avoid breaking changes. Example:

NestFactory.create(AppModule, { abortOnError: false })

Would you like to create a PR for this issue?

Isn't a better way of doing this would be to provide an interface NestExceptionsHandler an implementation of which can be passed into the options in nestfactory.create() and that exceptionhandler can be used in place of the default exception handler in exceptions-zone.js
export class ExceptionHandler implements NestExceptionHandler { handle(error) { // your custom error logic} } }
and then
await NestFactory.create(MainModule, {exceptionHandler: new ExceptionHandler()})
and then it can be used in exception-zone.js before calling teardown()
catch (e) { this.exceptionHandler.handle(e); teardown }.. Will that be a breaking change? @kamilmysliwiec

@princechauhan1992 what I've proposed (abortOnError) should actually cover the same set of use-cases. I mean, obviously when someone would enable abortOnError: true, the error would be re-thrown (instead of calling process.abort()), and so it would be possible to wrap the NestFactory.create() method with the try..catch blocks to catch and process the exception.

Sounds good @kamilmysliwiec. @larose @kamilmysliwiec I would like to create a pr for this, if you allow me.

Sure thing! PRs are more than welcome

Sounds good @kamilmysliwiec. @larose @kamilmysliwiec I would like to create a pr for this, if you allow me.

:+1: thanks!

PR https://github.com/nestjs/nest/pull/5327 is now merged and released as 7.5.0

Was this page helpful?
0 / 5 - 0 ratings