【问题标题】:Use GetLastError() to retrieve custom exception properties使用 GetLastError() 检索自定义异常属性
【发布时间】:2014-07-31 16:02:49
【问题描述】:

所以我创建了一个自定义异常类(我们称之为CustomException)以及一些在Exception 类中找不到的自定义属性。在 global.asax.cs 文件中有 Application_Error 方法,只要发生异常就会调用该方法。我正在使用Server.GetLastError() 来获取触发Application_Error 方法的异常。问题是Server.GetLastError() 只抓取一个Exception 对象,而不是与它的自定义属性一起被抛出的CustomException 对象。基本上,CustomException 在被Server.GetLastError() 检索时会被剥离为Exception 对象,从而丢失与CustomException 关联的自定义属性。

有没有办法让GetLastError() 实际检索CustomException 对象而不是精简的Exception 版本?这是为了将错误存储在数据库表中,其中包含比Exception 通常提供的更多信息。

Application_Error:

protected void Application_Error(object sender, EventArgs e)
{
    // This var is Exception, would like it to be CustomException
    var ex = Server.GetLastError();           

    // Logging unhandled exceptions into the database
    SystemErrorController.Insert(ex);

    string message = ex.ToFormattedString(Request.Url.PathAndQuery);

    TraceUtil.WriteError(message);
}

CustomException:

public abstract class CustomException : System.Exception
{        
    #region Lifecycle

    public CustomException ()
        : base("This is a custom Exception.")
    {
    }

    public CustomException (string message)
        : base(message)
    {
    }

    public CustomException (string message, Exception ex)
        : base(message, ex)
    {
    }

    #endregion

    #region Properties

    // Would like to use these properties in the Insert method
    public string ExceptionCode { get; set; }
    public string SourceType { get; set; }
    public string SourceDetail { get; set; }
    public string SystemErrorId { get; set; }

    #endregion        
}

【问题讨论】:

标签: c# exception global-asax getlasterror application-error


【解决方案1】:

只需将 Server.GetLastError 的结果转换为 CustomException:

var ex = Server.GetLastError() as CustomException;

请记住,在某些情况下,您的 CustomException 不可能是 StackTrace 中的顶级异常,在这种情况下,您需要浏览 InnerExceptions 以找到正确的异常。

请查看@scott-chamberlain 链接,了解如何设计自定义异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2016-01-07
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    相关资源
    最近更新 更多