Skip to content

[@sentry/node] AWS Lambda and other Serverless solutions support #1449

Closed

Description

@vietbui
  • @sentry/node version 4.0.0-beta.11
  • I'm using hosted Sentry

What is the current behavior?

I'm using @sentry/node to capture exception on AWS lambda function.

    .catch(err => {
      Sentry.captureException(err)
      context.fail()
    })

However, it kills the process when context.fail() is called and the exception does not end up in Sentry.

I could do a workaround like:

    .catch(err => {
      Sentry.captureException(err)
      setTimeout(() => context.fail(), 1000)
    })

What is the expected behavior?

It would be nice if I can do something like:

    .catch(err => {
      Sentry.captureException(err, () => context.fail())
    })

Or something globally handle callback.

Activity

  1. changed the title [-][raven-node] Callback after capture exception (or event, message)[/-] [+][raven-node] Callback after capturing exception (or event, message)[/+] on Jul 29, 2018
  2. kamilogorek commented on Aug 2, 2018

    @kamilogorek
    Contributor

    This may help I guess https://blog.sentry.io/2018/06/20/how-droplr-uses-sentry-to-debug-serverless (it's using old raven version, which had a callback, but I'm mostly pointing to a callbackWaitsForEmptyEventLoop flag.

    There's no official way yet, as we're still trying things out in beta, but it's doable with this code:

    import { init, getDefaultHub } from '@sentry/node';
    
    init({
      dsn: 'https://my-dsn.com/1337'
    });
    
    exports.myHandler = async function(event, context) {
      // your code
    
      await getDefaultHub().getClient().captureException(error, getDefaultHub().getScope());
      context.fail();
    }
  3. vietbui commented on Aug 6, 2018

    @vietbui
    Author

    @kamilogorek Thank you for the pointer. I'll give it a try and play back the learnings.

  4. vietbui commented on Aug 7, 2018

    @vietbui
    Author

    @kamilogorek You suggestion works. I'm looking forward to a more official way.

  5. changed the title [-][raven-node] Callback after capturing exception (or event, message)[/-] [+][@sentry/node] Callback after capturing exception (or event, message)[/+] on Aug 7, 2018
  6. HazAT commented on Sep 7, 2018

    @HazAT
    Member

    @vietbui
    In 4.0.0-rc.1 we introduced a function on the client called close, you call it like this:

    import { getCurrentHub } from '@sentry/node';
    
    getCurrentHub().getClient().close(2000).then(result => {
          if (!result) {
            console.log('We reached the timeout for emptying the request buffer, still exiting now!');
          }
          global.process.exit(1);
    })

    close will wait until all requests are sent, it will always resolve (result = false timeout was reached), up until the timeout is reached (in this example 2000ms).
    This is our official API.
    While the prev approach will still work, the close method works for all cases.

  7. vietbui commented on Sep 13, 2018

    @vietbui
    Author

    @HazAT Nice one. Thanks for all the hard work.

  8. vietbui commented on Sep 21, 2018

    @vietbui
    Author

    In 4.0.3 I call it like this in my lambda function:

    try {
      ...
    } catch (err) {
      await getCurrentHub().getClient().captureException(err, getCurrentHub().getScope())
      throw err
    }
    

    getDefaultHub() is no longer available.

  9. kamilogorek commented on Sep 24, 2018

    @kamilogorek
    Contributor

    @vietbui it's called getCurrentHub now, as we had to unify our API with other languages SDKs.

  10. vietbui commented on Sep 26, 2018

    @vietbui
    Author

    @kamilogorek Thanks for the clarification. There is a problem with getCurrentHub approach as somehow the scope I set up did not end up in Sentry.

    In the end I took a different approach as suggested by @HazAT to capture exception in my lambda functions:

    try {
      ...
    } catch (err) {
      Sentry.captureException(err)
      await new Promise(resolve => Sentry.getCurrentHub().getClient().close(2000).then(resolve))
      throw err
    }
    

    And it works perfectly.

  11. albinekb commented on Oct 3, 2018

    @albinekb

    Is this the recommended way to wait/force sentry to send events?

  12. kamilogorek commented on Oct 3, 2018

    @kamilogorek
    Contributor
  13. Andriy-Kulak commented on Nov 11, 2018

    @Andriy-Kulak

    @albinekb yes – https://docs.sentry.io/learn/draining/?platform=browser

    This solution does not work for me for some reason. It only works the first time in production when there is a cold start time and does not work after that. here is example code

    'use strict'
    
    const Sentry =  require('@sentry/node')
    Sentry.init({
      dsn: 'xxx',
      environment: process.env.STAGE
    });
    
    module.exports.createPlaylist = async (event, context, callback) => {
      context.callbackWaitsForEmptyEventLoop = false
      if(!event.body) {
        Sentry.captureException(error)
        await new Promise(resolve => Sentry.getCurrentHub().getClient().close(2000).then(resolve))
        return {
          statusCode: 500,
          headers: { 'Content-Type': 'text/plain' },
          body: 'Missing body parameters'
        }
      }
      return {
        statusCode: 200,
      }
    };
  14. albinekb commented on Nov 12, 2018

    @albinekb

    @Andriy-Kulak Thats also stated in the docs:

    After shutdown the client cannot be used any more so make sure to only do that right before you shut down the application.

    So I don't know how we can handle this in lambda where we don't know when the application will be killed. Best would be to drain sentry per request like we could with the old API?

  15. 57 remaining items

  16. esetnik commented on Jul 1, 2019

    @esetnik

    I have what I believe is a similar issue as @enapupe. If you call await client.flush(2000); in parallel only the first promise is resolved. This can happen in AWS lambda contexts where the client is reused among multiple concurrent calls to the handler.

    I am using code like this:

     let client = Sentry.getCurrentHub().getClient();
      if (client) {
        // flush the sentry client if it has any events to send
        log('begin flushing sentry client');
        try {
          await client.flush(2000);
        } catch (err) {
          console.error('sentry client flush error:', err);
        }
        log('end flushing sentry client');
      }

    But when I make two calls to my lambda function in rapid succession, I get:

      app begin flushing sentry client +2ms
      app begin flushing sentry client +0ms
      app end flushing sentry client +2ms
    

    You can see that the second promise is never resolved.

  17. enapupe commented on Jul 1, 2019

    @enapupe

    @esetnik I've filed an issue on that: #2131
    My currrent workaround is a wrapper flush fn that always resolves (based on a timeout):

    const resolveAfter = (ms: number) =>
      new Promise((resolve) => setTimeout(resolve, ms))
    
    const flush = (timeout: number) =>
      Promise.race([resolveAfter(timeout), Sentry.flush(timeout)])
    
  18. esetnik commented on Jul 1, 2019

    @esetnik

    @enapupe I added a note about your workaround in #2131. I believe it will cause a performance regression on concurrent flush.

  19. SarasArya commented on Aug 10, 2019

    @SarasArya

    In case anybody is having any issues.
    This works beautifully

  20. cibergarri commented on Dec 10, 2019

    @cibergarri

    @SarasArya @HazAT
    First of all... Thanks for sharing your solution! :)
    There is one callback of configureScope method that I guess it is supposed to be called before captureException but it is not being done in the same "thread".
    Couldn't this lead to the appearance of race conditions?

  21. SarasArya commented on Dec 11, 2019

    @SarasArya

    @cibergarri I don't think so, looks synchronous to me, in case you have an async method in there, then there would be race conditions.
    Consider is like .map of array's that the same thing happening here. In case you have issues wrapping your head around it. I hope that helps.

  22. kamilogorek commented on Dec 11, 2019

    @kamilogorek
    Contributor

    Yeah, it's totally fine to do that

  23. ajjindal commented on Sep 21, 2020

    @ajjindal

    Update: Sentry now supports automated error capture for Node/Lambda environments: https://docs.sentry.io/platforms/node/guides/aws-lambda/

  24. armando25723 commented on Nov 9, 2020

    @armando25723

    I'm using @sentry/serverless like this:

    const Sentry = require("@sentry/serverless");
    Sentry.AWSLambda.init({
      dsn: process.env.SENTRY_DSN,
      tracesSampleRate: 1.0,
      environment: appEnv
    });
    
    exports.main = Sentry.AWSLambda.wrapHandler(async (event, context) => {
         try{
               //my code
         }catch(error){
              Sentry.captureException(error);
              await Sentry.flush(3000);
         }
    
    });
    

    It does not work on lambda.
    In my testing env it was working but in prod where there is a lot a concurrent executions and the containers are reuse it is logging just about 10% of the total amount.

    Any advice?

  25. marshall-lee commented on Nov 10, 2020

    @marshall-lee
    Contributor

    @armando25723

    Please tell how did your measure that it loses the exception events? Do you have a code sample of how such lost exception was thrown? Need more context.

  26. armando25723 commented on Nov 10, 2020

    @armando25723
    const Sentry = require("@sentry/serverless"); // "version": "5.27.3"
    Sentry.AWSLambda.init({
      dsn: process.env.SENTRY_DSN,
      tracesSampleRate: 1.0,
      environment: appEnv
    });
    exports.main = Sentry.AWSLambda.wrapHandler(async (event, context) => {
         try{
               throw new Error('Test Error');
         }catch(error){
              Sentry.captureException(error);
              await Sentry.flush(3000);
         }
    });
    
    

    What is happening?
    If the function is invoked several times with short interval between invocations the event is only logged once.
    If the time interval between invocations is larger all events are logged.

    I assume that the problem is when the invocation is over a reused container.

    I have tried also
    await Sentry.captureException(error);
    and:
    await Sentry.flush();
    and without flushing
    same result

  27. armando25723 commented on Nov 11, 2020

    @armando25723

    @marshall-lee what do you recomend? Should I create an issue, I'm stuck here.

  28. ajjindal commented on Nov 11, 2020

    @ajjindal

    @armando25723 Looks like the server is responding with 429 (too many exceptions) while sending these events. We throw that in case of over quota/rate limiting scenarios. Do you know if you are sequentially sending errors or over quota? We can debug further if you think these are real error events getting dropped and you are under our 5k limit for the free tier.

  29. armando25723 commented on Nov 11, 2020

    @armando25723

    @ajjindal all other projects are working fine with sentry. The organization slug is "alegra", project name is mail-dispatch-serverless under #mail-micros. We have been using sentry for a long time, but first time with serverless. This is not free tier, I can't tell you exactly which plan we are using but it is a paid one.
    It will be nice if you could help me to debug further.
    Thanks for reply : )

    PD: is Team Plan

  30. dborstelmann commented on Nov 13, 2021

    @dborstelmann

    I'm having the same issue here, doing await Sentry.flush(1000); after captureException is not sending the errors to sentry. Filed a new issue here if anyone has any advice: #4155

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions