由自定义HandleErrorAttribute捕获的ActionFilterAttribute上的MVC5异常会更改StackTrace

时间:2016-06-16 13:21:54

标签: asp.net-mvc

我有一个像这样的ActionFilterAttribute

public class DataModelAttribute : ActionFilterAttribute
{   
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        ...
        throw filterContext.Exception;  //StackTrace is fine (pointing to my controller)
    }
}

我有一个像这样的全局错误过滤器:

public class OncHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        var ex = context.Exception; //Here StackTrace points to DataModelAttribute file
    }
}

所以我丢失了原来的StackTrace ......我怎么能保留它呢?

2 个答案:

答案 0 :(得分:1)

我猜你不能按MSDN的建议使用throw代替throw filterContext.Exception

因此,您应抛出一个新的异常,并将原始异常作为内部异常包含在建议here中。

答案 1 :(得分:0)

在您的情况下,它看起来像这样:

 public class HandleExceptionErrors : ActionFilterAttribute, IExceptionFilter
{

    private Type _exceptionType;
    public HandleExceptionErrors(Type exceptionType)
    {
        _exceptionType = exceptionType;
    }
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception.GetType() != _exceptionType) return;


        filterContext.ExceptionHandled = true;
        var data= filterContext.Exception +" , "+ filterContext.Exception.InnerException+" , "+filterContext.Exception.Message +" , "+filterContext.Exception.StackTrace;

    }
}