Luc*_*rre 1 c# asp.net error-handling
我觉得我想得太多了,或者可能走错了路,但从高层次来说,我要做的就是捕获应用程序中抛出的错误,将它们记录到数据库中,然后重定向到一个软错误页。
在我的 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");
}
}
Run Code Online (Sandbox Code Playgroud)
错误日志是我创建的一个类,用于执行记录插入等操作。
现在我遇到的问题是,如果数据库有问题,比如它处于脱机状态,存储过程中的错误等,我就会陷入无限循环插入的错误中。
我试图提出解决此行为的解决方案可能是检查是否已抛出错误,如果已抛出,请不要尝试尝试插入记录,但我无法找到太多相关信息.
同样,也许我不会以正确的方式解决这个问题?任何帮助将不胜感激。先谢谢了。
实际上可以这样做,但我真的不认为这是一个好主意。
理论上你可以Marshal.GetExceptionPointers()用来检测它。如果返回IntPtr.Zero,则可能表示飞行中没有异常;否则,这可能意味着有。
我说“可能”是因为 MSDN 文档Marshal.GetExceptionPointers()在评论中说:
GetExceptionPointers 仅用于编译器支持结构化异常处理 (SEH)。
所以这对我来说听起来像是一个很大的脂肪“不要使用这个”。
有了这个条件,这个程序实际上会告诉你异常是否正在运行,而不使用 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.");
}
}
}
Run Code Online (Sandbox Code Playgroud)