-1

因此,我创建了一个自定义异常类(我们称之为CustomException)以及Exception该类中未找到的一些自定义属性。在 global.asax.cs 文件中有Application_Error一个在异常发生时调用的方法。我Server.GetLastError()用来抓取触发该Application_Error方法的异常。问题是Server.GetLastError()它只抓取一个Exception对象,而不是CustomException与它的自定义属性一起被抛出的对象。基本上被检索时CustomException被剥离为一个对象,因此失去了与 关联的自定义属性。ExceptionServer.GetLastError()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        
}
4

1 回答 1

0

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

var ex = Server.GetLastError() as CustomException;

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

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

于 2014-07-31T22:59:26.157 回答