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

标签 c# asp.net event-log

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

我可以自己捕获异常并将其写入事件日志,但我担心我无法保证 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/

相关文章:

c# - 以编程方式从 WPF 中的代码中删除删除线文本装饰

c# - JObject - 动态添加新对象

c# - usercontrol 中的所有控件都为 null

c# - 从路径读取事件日志文件

c# - 在网格布局中创建动态按钮 - 创建幻方 UI

c# - 如何修改 Environment.CommandLine 属性?

asp.net - 为什么我要在 MVP 中对业务层进行单元测试

c# - 从 ASP.NET Web API 层使用的方法中抛出或不抛出异常

.net - 使用 EventLog 对象会导致安全漏洞?

wmi - 什么是 win32_NTLogEvent 时间生成格式