c# - 捕获 ASP.NET C# 中的所有异常,而不是捕获 `try{} catch{}` block 中的每个方法

标签 c# asp.net windows try-catch

是否有更好的方法可以在一个地方捕获所有异常,而无需为每个方法编写 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/

相关文章:

c++ - 在 Linux 中获取自纪元以来的秒数

c# - asp.net 缓存限制?

c# - 如何在本地选择默认区域性 -(以及为什么不在 Azure 上运行时不选择)

c# - VB.NET,创建一个返回类型为泛型的函数?

c# - HtmlEditorExtender 的回发问题

c# - 始终创建一个新的 HttpContextWrapper 是否安全?

windows - 为什么我在 Windows 上运行 Perl one liner 时出现“找不到字符串终止符 "'”错误

windows - 为什么在使用 Vagrant 配置 Windows 7 VM 时 Chocolatey 无法安装?

c# - 使 Javascript 代码在 Page Start 上运行

c# - select from where 加无条件同时选择