c# – 抛出错误但不向用户显示错误的最简洁方法(没有自定义错误页面)
作者:互联网
我正在运行一些只需要运行一次的代码,但它依赖于外部资源而且可能会失败.我希望错误出现在事件日志中,但我不希望用户看到它.我想尽可能避免使用自定义错误页面.
我可以捕获异常并将其自己写入事件日志,但我担心我不能保证asp.net事件源的名称会是什么(它似乎会根据框架版本而改变.)我也是无法创建我自己的事件源,因为它需要管理权限.
我目前正在努力的方法是一个黑客(它还没有工作),它看起来像这样:
public void Init(HttpApplication context)
{
try
{
throw new Exception("test"); // This is where the code that errors would go
}
catch (Exception ex)
{
HttpContext.Current.Application.Add("CompilationFailed", ex);
}
}
private void context_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Application.AllKeys.Contains("CompilationFailed"))
{
// It failed on Init - we can't throw an exception there so lets try it here
var origEx = (Exception)HttpContext.Current.Application["CompilationFailed"];
// Only ever do this once
HttpContext.Current.Application.Remove("CompilationFailed");
// This should just look like a normal page load to the user
// - it will be the first request to the site so we won't be
// interrupting any postbacks or anything
HttpContext.Current.Response.AddHeader("Location", "/");
HttpContext.Current.Response.StatusCode = 301;
try
{
HttpContext.Current.Response.End();
}
catch (ThreadAbortException ex)
{
throw origEx;
}
}
}
理想情况下,我真正想要的是IIS中的RecordException()方法,如果存在这样的话.
解决方法:
我建议使用Elmah for ASP.NET.
标签:c,asp-net,event-log 来源: https://codeday.me/bug/20190517/1121891.html