Exceptions thrown on async providers in Request scope are not handled.
See original GitHub issueBug Report
maybe related to https://github.com/nestjs/nest/issues/1126 https://github.com/nestjs/nest/issues/761
Current behavior
When routes with async providers are used request crashes and client never gets any response. Error shows up as UnhandledPromiseRejectionWarning in console
Input Code
replication repo https://github.com/dynamikus/replicate-nestjs-request-scope-usefactory-error
{
provide: SomeService,
scope: Scope.REQUEST,
useFactory: async () => {
throw new Error('Boom');
return new Somervice();
},
}
Expected behavior
Errors thrown from async provider should buble up to the global exception handler. So we can gracefully respond to the client.
Possible Solution
Sorry tried to be able to figure out for a solution but I am not familiar with nestjs core. Error bubbles up to here https://github.com/nestjs/nest/blob/master/packages/core/router/router-explorer.ts#L195 We need to wrap with try and catch the handler method and apply the exception filter (which I am not sure what the correct nestjs to handle this. 😦 ) I monkey patched a solution but I am not sure if this is the proper nestjs way to handle this. Let me know if this approach is Ok and I will open a pr.
if (isRequestScoped) {
const handler = async <TRequest, TResponse>(
req: TRequest,
res: TResponse,
next: () => void,
) => {
const contextId = createContextId();
this.registerRequestProvider(req, contextId);
try {
const contextInstance = await this.injector.loadPerContext(
instance,
module,
collection,
contextId,
);
this.createCallbackProxy(
contextInstance,
contextInstance[methodName],
methodName,
moduleKey,
requestMethod,
contextId,
instanceWrapper.id,
)(req, res, next);
paths.forEach(path => {
const fullPath = stripSlash(basePath) + path;
routerMethod(stripSlash(fullPath) || '/', handler);
});
} catch (error) {
const host = new ExecutionContextHost([req, res]);
const exceptionFilter = this.exceptionsFilter.create(
instance,
() => {},
methodName,
contextId,
instanceWrapper.id,
);
exceptionFilter.next(error, host);
}
};
return;
}
Environment
Nest version: 6.2.4
For Tooling issues:
- Node version: 12.0.1
- Platform: Windows
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (3 by maintainers)
Let me reopen this and look at the best possible solution
Fixed in 6.4.0. Keep in mind that these exceptions will be catchable only by statically scoped exception filters 😃