【发布时间】:2012-02-14 15:56:15
【问题描述】:
我正在尝试构建一个动态类型列表,该列表实际上是 ExceptionLogCondition 类型,这是一个定义需要解除的异常类型和特定异常类型的可选条件谓词的类。
问题在于将异常传递给IsConditionValid(T e) 方法。我总是得到这个例外:
最好的重载方法匹配 'MvcApplication.ErrorLogCondition.IsConditionValid(Exceptions.AjaxOnlyViolationException)' 有一些无效的参数
堆栈跟踪:
在 CallSite.Target(Closure , CallSite , Object , Exception ) 在 System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,Tret](CallSite 站点,T0 arg0,T1 arg1) 在 CONCENTRA.MOS.MvcApplication.ErrorLog_Filtering(对象发送者, C:_teamprojects\Main\Source\Global.asax.cs:line 中的 ExceptionFilterEventArgs e) 213 在 Elmah.ErrorLogModule.OnFiltering(ExceptionFilterEventArgs args) 在 Elmah.ErrorLogModule.LogException(Exception e, HttpContext 上下文) 在 Elmah.ErrorLogModule.OnError(Object sender, EventArgs args) 在 System.EventHandler.Invoke(Object sender, EventArgs e)
在 System.Web.HttpApplication.RaiseOnError()
代码如下:
public class MvcApplication : System.Web.HttpApplication
{
protected void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e)
{
var exceptionsToDismiss = new List<dynamic>() {
new ErrorLogCondition<Exceptions.AjaxOnlyViolationException>(),
new ErrorLogCondition<WebsiteException>(c => c.LogError == true)
};
foreach (var exd in exceptionsToDismiss)
{
if(((Type)exd.ExceptionType).Equals(e.Exception.GetBaseException().GetType()) &&
exd.IsConditionValid(e.Exception.GetBaseException()))
// The second condition fails even though the type is correct (see first if condition).
e.Dismiss();
}
}
}
public class ErrorLogCondition<T> where T : Exception, new() {
public Type ExceptionType {get;set;}
public Predicate<T> ExceptionTypeCondition { get; set; }
public ErrorLogCondition() {
ExceptionType = typeof(T);
}
public ErrorLogCondition(Predicate<T> c)
{
ExceptionType = typeof(T);
ExceptionTypeCondition = c;
}
public bool IsConditionValid(T e)
{
return ExceptionTypeCondition == null || ExceptionTypeCondition.Invoke(e);
}
}
我的直觉表明我可能做得有点过头了。所以我愿意接受其他建议。不过我也想知道为什么这不起作用。
【问题讨论】:
-
您可能应该为
ErrorLogCondition的ExceptionType属性设置setter 私有:public Type ExceptionType { get; private set; }
标签: c# generics dynamic exception-handling