是否有更好的方法可以在一个地方捕获所有异常,而无需为每个方法编写 try{} catch{}
?
最佳答案
您可以通过覆盖 Global.asax
中的 Application_Error
来捕获应用程序中的异常。但是,使用这种方法,您无法像使用常规 try catch
block 那样处理这些异常。
您可以记录它
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// if there's an Inner Exception we'll most likely be more interested in that
if (ex .InnerException != null)
{
ex = ex .InnerException;
}
// filter exception using ex.GetType() ...
// log exception ...
// Clear all errors for the current HTTP request.
HttpContext.Current.ClearError();
}
和/或重定向
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// process exception
// redirect
HttpContext.Current.ClearError();
Response.Redirect("~/Error.aspx", false);
return;
}
这就是你能做的一切。
关于c# - 捕获 ASP.NET C# 中的所有异常,而不是捕获 `try{} catch{}` block 中的每个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27374891/