[英]c# How to Check if an Exception Was Already Thrown
我觉得我已经在考虑这个问题,或者可能是错误的方式,但我想要做的就是捕获我的应用程序中抛出的错误,将它们记录在数据库中,然后重定向到软错误页。
在我的Global.asax中,我有以下内容:
protected void Application_Error(object sender, EventArgs e)
{
try
{
ErrorLog error = new ErrorLog(Server.GetLastError().GetBaseException(), true);
Response.Redirect("/error.aspx?id=" + error.ID);
}
catch(Exception err)
{
Response.Redirect("/error.aspx");
}
}
错误日志是我创建的一个类,它执行记录插入和类似的东西。
现在我遇到的问题是,如果数据库存在某些问题,例如它处于脱机状态,存储过程中的错误等,我会陷入无限循环的错误插入状态。
我试图解决此问题的解决办法是检查是否已经抛出错误,如果是这样,请不要尝试尝试记录插入,但我无法在此处找到太多内容。
再说一次,也许我不会以正确的方式去做这件事? 任何帮助将不胜感激。 先谢谢你。
实际上可以这样做,但我真的认为这不是一个好主意。
理论上你可以使用Marshal.GetExceptionPointers()
来检测它。 如果它返回IntPtr.Zero,则可能意味着在飞行中没有例外; 否则,它可能意味着有。
我说“可能”,因为Marshal.GetExceptionPointers()
的MSDN文档在备注中说:
仅为编译器支持结构化异常处理(SEH)公开GetExceptionPointers。
所以这听起来像一个大胖子“不要用这个”给我。
有了这个附带条件,这个程序实际上会告诉你一个异常是否在飞行中,而不使用try / catch来执行此操作:
警告:提前讨厌的代码
using System;
using System.Runtime.InteropServices;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
try
{
using (new Test())
{
// All is well.
}
using (new Test())
{
throw new InvalidOperationException("Eeep");
}
}
catch (Exception ex)
{
Console.WriteLine("Exception detected: " + ex.Message);
}
}
}
sealed class Test: IDisposable
{
public void Dispose()
{
Console.WriteLine(
Marshal.GetExceptionPointers() == IntPtr.Zero
? "Disposing test normally."
: "Disposing test because of an exception.");
}
}
}
您可以检查您是否已经在该页面上,并且只有在您不是这样时才重定向:
string cTheFile = HttpContext.Current.Request.Path;
if(!cTheFile.EndsWith("error.aspx", StringComparison.InvariantCultureIgnoreCase))
Response.Redirect("/error.aspx");
使用ErrorLogDBInsertException覆盖Exception类,如果DB内容不好,则抛出此类。 捕获特定错误
protected void Application_Error(object sender, EventArgs e)
{
try
{
ErrorLog.Log();
Response.Redirect("/error.aspx?id=" + error.ID);
}
catch(ErrorLogDBInsertException err)
{
try
{
// here you can log into event log
}
catch {}
Response.Redirect("/SimpleNoDBCallPage_error.aspx");
}
catch(Exception err)
{
Response.Redirect("/PageThatCallsDB_error.aspx");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.