gpt4 book ai didi

c# - 抛出错误但不向用户显示错误的最简洁方法(没有自定义错误页面)

转载 作者:太空狗 更新时间:2023-10-29 23:08:31 25 4
gpt4 key购买 nike

我正在运行一些只需要运行一次的代码,但它依赖于外部资源并且可能会失败。我希望错误出现在事件日志中,但我不希望用户看到它。如果可能,我想避免使用自定义错误页面。

我可以自己捕获异常并将其写入事件日志,但我担心我无法保证 asp.net 事件源的名称是什么(它似乎会根据框架版本而改变。 ) 我也无法创建自己的事件源,因为这需要管理权限。

我目前正在努力的方法有点像 hack(目前还行不通),它看起来像这样:

    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用于 ASP.NET。

关于c# - 抛出错误但不向用户显示错误的最简洁方法(没有自定义错误页面),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17750936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com