【发布时间】: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
}
【问题讨论】:
-
您是否尝试过使用调试器验证
ex的实际类型或InnerException属性的实际类型? -
这取决于
SystemErrorController.Insert(ex);的实现,当您将其传递给Insert时,在这里设置您的特定类型并没有帮助,而且您的异常确实应该有a protected constructor that calls the base protected constructor and be marked asSerializeable。
标签: c# exception global-asax getlasterror application-error