我有一个自定义异常类,它将包装抛出的任何其他异常。通过这种方式,我将始终知道异常已处理,并且所有其他方法和层将知道将异常传递到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块或默认调用它?您会注意到我没有需要添加或编辑的自定义信息,此代码可以针对整个应用程序中的每个基本异常运行。
答案 0 :(得分:0)
您的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();
}
}
}
}