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

This is the default empty lambda function project :

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 ?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With