question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Exceptions thrown on async providers in Request scope are not handled.

See original GitHub issue

Bug 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:closed
  • Created 4 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
kamilmysliwieccommented, May 29, 2019

Let me reopen this and look at the best possible solution

1reaction
kamilmysliwieccommented, Jul 1, 2019

Fixed in 6.4.0. Keep in mind that these exceptions will be catchable only by statically scoped exception filters 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Spring Async Uncaught Exception handler - Stack Overflow
@Async methods can be configured with a custom Executor to log any thrown exceptions. The following code implements this pattern.
Read more >
Are You Handling Exceptions in Kotlin Coroutines Properly?
In this article I will try to show situations where you need to be more cautious about exceptions and show some best practices...
Read more >
Async Scope | MuleSoft Documentation
The Async scope is a branch processing block that executes simultaneously with the main flow. The main flow continues to execute while it...
Read more >
Exception Handling | RESTful Java with JAX-RS 2 ... - dennis-xlc
Thrown exceptions are handled by the JAX-RS runtime if you have registered an exception mapper. Exception mappers can convert an exception to an...
Read more >
17. Web MVC framework - Spring
Beans whose lifecycle is scoped to the current HTTP request or HTTP Session . ... pick up exceptions that are thrown during processing...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found