是否有可能调用所有Catch块的代码而不手动添加它?

本文关键字:添加 代码 调用 有可能 Catch 是否 | 更新日期: 2023-09-27 18:07:18

我有一个自定义异常类,它将封装抛出的任何其他异常。这样我就知道异常被处理了所有其他的方法和层都知道要把异常传递给UI。然而,当第一次抛出异常时,我希望每次都做同样的事情。

    catch (TestWebException)
    {
        throw;
    }
    catch (Exception ex)
    {
        LogException(ex, System.Reflection.MethodInfo.GetCurrentMethod().Name);
        var x = new TestWebException(ex.Message);
        x.SourceException = ex;
        throw x;
    }

是否有一种机制将此逻辑注入每个catch块或默认调用它?您会注意到没有需要添加或编辑的自定义信息,这段代码可以在整个应用程序中的每个基本异常中运行。

是否有可能调用所有Catch块的代码而不手动添加它?

是有可能的。您需要在FilterConfig.cs

中注册exceptionfilterattribute。

你的FilterConfig.cs应该如下所示:

    public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new TestWebExceptionFilterAttribute()); // Custom Exception & Log Handling
    }
}

类TestWebExceptionFilterAttribute应该如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;
using System.Data.Entity;
using ITFort.TestWeb.Models.DBFirst.Authorization;
namespace ITFort.TestWeb.Filters
{
    public class TestWebExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        using (TestWebAuthorizationEntities db = new TestWebAuthorizationEntities())
        {
            ExceptionDatabaseTable exception = new ExceptionDatabaseTable;
            exception.UserId = WebSecurity.CurrentUserId;
            exception.Controller = filterContext.RouteData.Values["controller"].ToString();
            exception.Action = filterContext.RouteData.Values["action"].ToString();
            exception.Message = filterContext.Exception.Message;
            exception.StackTrace = filterContext.Exception.StackTrace;
            exception.ErrorDateTime = DateTime.Now;
            db.Entry(exception).State = EntityState.Added;
            db.SaveChanges();
        }
    }
}
}