HandleErrorAttribute的自定义(拦截器的使用)

mvc中提供了HandleErrorAttribute特性,该特性用于处理由操作方法引发的异常。

我们可以继承HandleErrorAttribute,再对OnException进行重写。将错误写入到事件日志中。

public class HandleErrorWithELMAHAttribute:HandleErrorAttribute
{
public override void OnException(ExceptionContext Context)
{
base.OnException(Context);
dynamic e
= Context.Exception;
if (!Context.ExceptionHandled)
return;
LogException(e);

}

private static void LogException(Exception e)
{
HttpContext context
= HttpContext.Current;
string path="~/1.txt";
path
=context.Server.MapPath(path);
StreamWriter STRW
= File.AppendText(path);
STRW.WriteLine(e.Message);
STRW.Flush();
STRW.Close();
STRW.Dispose();

}
}

对于此我们可以用公共的错误日志组件:比如log4net,Elmah。

原文地址:https://www.cnblogs.com/linjiancun/p/1827937.html