简体   繁体   English

AWS .net Core Lambda项目中的全局异常处理程序?

[英]Global exception handler in AWS .net Core Lambda project?

Simplification — I've created an empty AWS Lambda project with .net CORE : 简化 - 我使用.net CORE创建了一个空的AWS Lambda项目:

在此输入图像描述

This is the default empty lambda function project : 这是默认的空lambda函数项目:

在此输入图像描述

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 问题是异常被引发,但它永远不会触发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 ? 为什么在存在未处理的异常时不会调用CurrentDomain_UnhandledException

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. 我使用的解决方法是将我的FunctionHandler包装在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. 因为这是lambda函数中唯一的入口点,所以在这里抛出的任何东西都会被捕获......实际上就像我的目的一样,它就像一个全局处理程序。

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 AWS将再次重试该功能,然后您可以在X重试后发送DeadLetterQueue
  2. You get the exception in your CloudWatch Logs 您在CloudWatch Logs中获得例外

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM