Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global exception handler in AWS .net Core Lambda project?

Simplification — I've created an empty AWS Lambda project with .net CORE :

enter image description here

This is the default empty lambda function project :

enter image description here

I want to catch all exception in the app , globally.

So I've created a method that generates an exception, and added a global application handler :

Complete code :

 public class Function
    {
        void CreateException()
        {
            var z = 0;
            var a = 2 / z;
            Console.Write(a);
        }

        public Function()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        public void FunctionHandler(object input, ILambdaContext context)
        {
            CreateException();
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // � It never gets here
        }

    }

The problem is that the exception is raised , but it never fires CurrentDomain_UnhandledException

Question:

Is this the right way of catching global exceptions ? and why doesn't CurrentDomain_UnhandledException invoked when there is an unhandled exception ?

like image 732
Royi Namir Avatar asked Feb 27 '19 10:02

Royi Namir


1 Answers

While I cannot answer why this isn't working, I can tell you I have done as a workaround.

The workaround I have used is to wrap my FunctionHandler in a try/catch. Since this is the only entrypoint in the lambda function, anything that gets thrown in here will be caught...effectively acting like a global handler for my purposes.

public void FunctionHandler(object input, ILambdaContext context)
{
    try
    {
        CreateException();
    }
    catch (Exception e)
    {
        // Handle your 'uncaught' exceptions here and/or rethrow if needed
        Console.WriteLine(e);
        throw;
     }
}

You would likely want to rethrow so that:

  1. AWS will retry the function again, then you can send it DeadLetterQueue after X retries
  2. You get the exception in your CloudWatch Logs
like image 109
TrialAndError Avatar answered Oct 14 '22 06:10

TrialAndError