如何编写自定义 C# 属性来处理处理程序中的异常

co2*_*f2e 5 c#

我创建了一个这样的自定义属性类

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class AMemento : Attribute
    {

        public void method(){
        try {

        }
        catch (Exception) {

        }}
    }
Run Code Online (Sandbox Code Playgroud)

并且我计划在处理程序中使用此自定义属性来捕获发生的任何异常,如下所示

    [AMemento]
    [Authorize]
    public JsonResult GetWeatherData()
    {
         //// code here which throw an exception
    }
Run Code Online (Sandbox Code Playgroud)

我想知道如何完成自定义属性类以捕获 GetWeatherData() 处理程序中抛出的异常。是否可以像在 python 中那样实现高阶函数?

Ale*_*exC 5

在 MVC 框架中有HandleErrorAttribute类。这可以扩展和覆盖OnException方法。一个很好的例子是在Elmah MVC项目中,他们有一个HandleErrorAttribute类。

这个问题还提供了一些 HandleErrorAttribute 的例子,同样在 ELMAH 的上下​​文中,但应该相对明显的是,在覆盖 OnException 时,您可以为 MVC 操作提供自定义异常逻辑。