https://docs.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/aspnet-error-handling

Overview

ASP.NET applications must be able to handle errors that occur during execution in a consistent manner. ASP.NET uses the common language runtime (CLR), which provides a way of notifying applications of errors in a uniform way. When an error occurs, an exception is thrown. An exception is any error, condition, or unexpected behavior that an application encounters.

In the .NET Framework, an exception is an object that inherits from the System.Exception class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the call stack to a place where the application provides code to handle the exception. If the application does not handle the exception, the browser is forced to display the error details.

As a best practice, handle errors in at the code level in Try/Catch/Finally blocks within your code. Try to place these blocks so that the user can correct problems in the context in which they occur. If the error handling blocks are too far away from where the error occurred, it becomes more difficult to provide users with the information they need to fix the problem.

Exception Class

The Exception class is the base class from which exceptions inherit. Most exception objects are instances of some derived class of the Exception class, such as the SystemException class, the IndexOutOfRangeException class, or the ArgumentNullException class. The Exception class has properties, such as the StackTrace property, the InnerException property, and the Message property, that provide specific information about the error that has occurred.

Exception Inheritance Hierarchy

The runtime has a base set of exceptions deriving from the SystemException class that the runtime throws when an exception is encountered. Most of the classes that inherit from the Exception class, such as the IndexOutOfRangeException class and the ArgumentNullException class, do not implement additional members. Therefore, the most important information for an exception can be found in the hierarchy of exceptions, the exception name, and the information contained in the exception.

Exception Handling Hierarchy

In an ASP.NET Web Forms application, exceptions can be handled based on a specific handling hierarchy. An exception can be handled at the following levels:

  • Application level
  • Page level
  • Code level

When an application handles exceptions, additional information about the exception that is inherited from the Exception class can often be retrieved and displayed to the user. In addition to application, page, and code level, you can also handle exceptions at the HTTP module level and by using an IIS custom handler.

Application Level Error Handling

You can handle default errors at the application level either by modifying your application's configuration or by adding an Application_Error handler in the Global.asax file of your application.

You can handle default errors and HTTP errors by adding a customErrors section to the Web.config file. The customErrors section allows you to specify a default page that users will be redirected to when an error occurs. It also allows you to specify individual pages for specific status code errors.

<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="ErrorPage.aspx?handler=customErrors%20section%20-%20Web.config">
<error statusCode="404" redirect="ErrorPage.aspx?msg=404&amp;handler=customErrors%20section%20-%20Web.config"/>
</customErrors>
</system.web>
</configuration>

Unfortunately, when you use the configuration to redirect the user to a different page, you do not have the details of the error that occurred.

通过web.config中的配置,跳转页面,是不带错误的detail的。

However, you can trap errors that occur anywhere in your application by adding code to the Application_Error handler in the Global.asax file.

void Application_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError(); if (exc is HttpUnhandledException)
{
// Pass the error on to the error page.
Server.Transfer("ErrorPage.aspx?handler=Application_Error%20-%20Global.asax", true);
}
}

Page Level Error Event Handling

A page-level handler returns the user to the page where the error occurred, but because instances of controls are not maintained, there will no longer be anything on the page. To provide the error details to the user of the application, you must specifically write the error details to the page.

You would typically use a page-level error handler to log unhandled errors or to take the user to a page that can display helpful information.

This code example shows a handler for the Error event in an ASP.NET Web page. This handler catches all exceptions that are not already handled within try/catch blocks in the page.

private void Page_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError(); // Handle specific exception.
if (exc is HttpUnhandledException)
{
ErrorMsgTextBox.Text = "An error occurred on this page. Please verify your " +
"information to resolve the issue."
}
// Clear the error from the server.
Server.ClearError();
}

After you handle an error, you must clear it by calling the ClearError method of the Server object (HttpServerUtility class), otherwise you will see an error that has previously occurred.

Application_Error() not firing

If you have <customErrors mode="Off" /> while debugging, the code won't reach to Application_Error event because exception is displayed inside browser right away.

If you want to reach Application_Error while debugging, you want to enable custom error -

<customErrors mode="On" defaultRedirect="~/Error.aspx" />

ASP.NET Global.asax Application_Error works but not when using the Error event

I'll up vote this for the first comment, but I don't believe the second part is true, I'm currently running my application with out the CustomErrors element in my webconfig and it's hitting the Error handler fine.

没有customErrors这个配置,应该也能触发application_error的

Page_Error not firing

Page_PreInit & OnPreInit - whats the difference?

make sure the AutoEventWireup is set to true

ASP.NET OnError not catching ConfigurationErrorsException

I peeked into the source code for ProcessRequestMain. There is a try...catch block in this method which catches any ConfigurationException and throws it again (look into line 4680). All other Exceptions are handed over to HandleError method which will call OnError. (Also ThreadAbortException is handled separately which is not your concern here.)

This is why you can't capture ConfigurationException (and ConfigurationErrorsException which is inherited from ConfigurationException) using either OnError method or Error event in an ASP.NET page.

可以在application_error中捕获这种异常。

Using ELMAH

ELMAH (Error Logging Modules and Handlers) is an error logging facility that you plug into your ASP.NET application as a NuGet package. ELMAH provides the following capabilities:

  • Logging of unhandled exceptions.
  • A web page to view the entire log of recoded unhandled exceptions.
  • A web page to view the full details of each logged exception.
  • An email notification of each error at the time it occurs.
  • An RSS feed of the last 15 errors from the log.

Before you can work with the ELMAH, you must install it. This is easy using the NuGet package installer. As mentioned earlier in this tutorial series, NuGet is a Visual Studio extension that makes it easy to install and update open source libraries and tools in Visual Studio.

ASP.NET Error Handling的更多相关文章

  1. Error Handling in ASP.NET Core

    Error Handling in ASP.NET Core 前言  在程序中,经常需要处理比如 404,500 ,502等错误,如果直接返回错误的调用堆栈的具体信息,显然大部分的用户看到是一脸懵逼的 ...

  2. Erlang error handling

    Erlang error handling Contents Preface try-catch Process link Erlang-way error handling OTP supervis ...

  3. MySQL Error Handling in Stored Procedures 2

    Summary: this tutorial shows you how to use MySQL handler to handle exceptions or errors encountered ...

  4. setjmp()、longjmp() Linux Exception Handling/Error Handling、no-local goto

    目录 . 应用场景 . Use Case Code Analysis . 和setjmp.longjmp有关的glibc and eglibc 2.5, 2.7, 2.13 - Buffer Over ...

  5. Error Handling

    Use Exceptions Rather Than Return Codes Back in the distant past there were many languages that didn ...

  6. Error Handling and Exception

    The default error handling in PHP is very simple.An error message with filename, line number and a m ...

  7. Clean Code–Chapter 7 Error Handling

    Error handling is important, but if it obscures logic, it's wrong. Use Exceptions Rather Than Return ...

  8. [RxJS] Error handling operator: catch

    Most of the common RxJS operators are about transformation, combination or filtering, but this lesso ...

  9. MySQL Error Handling in Stored Procedures---转载

    This tutorial shows you how to use MySQL handler to handle exceptions or errors encountered in store ...

随机推荐

  1. spring声明式的事务管理

    spring支持声明式事务管理和编程式事务管理两种方式. 编程式事务使用TransactionTemplate来定义,可在代码级别对事务进行定义. 声明式事务基于aop来实现,缺点是其最细粒度的事务声 ...

  2. Tarjan 总结

    Tarjan 基础 dfn[i]: 在dfs中该节点被搜索的次序(时间戳). low[i]: 为i或i的子树能够追溯到的最早的栈中节点的次序号. 当 dfn[i] == low[i] 时,为i或i的子 ...

  3. 术语-MOSS-微软协作工具:MOSS(微软协作工具)

    ylbtech-术语-MOSS-微软协作工具:MOSS(微软协作工具) MOSS -- Microsoft Office Sharepoint Server,是一款为企业客户而设计的.基于web的内容 ...

  4. C#-Newtonsoft.Json生成复杂JSON

    官方文档:https://www.newtonsoft.com/json/help/html/SerializeObject.htm 一种方式就可以生成所有的 JSON Collection -> ...

  5. 关于css3 Animation动画

    在介绍animation之前有必要先来了解一个东西,那就是“keyframes”,我们把他叫做“关键帧”: 在使用transition制作一个简单的transition效果时,包括了初始属性,最终属性 ...

  6. JDK 与 JRE

    JDK就是Java Development Kit.简单的说JDK是面向开发人员使用的SDK,它提供了Java的开发环境和运行环境.SDK是Software Development Kit 一般指软件 ...

  7. 小程序UI自动化(一):appium小程序自动化尝试

    appium 进行 小程序自动化尝试: 由于工作中进行app自动化用的是appium,故首先尝试用appium进行小程序自动化,以美团小程序为例(python脚本实现) 一.配置基础信息 启动微信ap ...

  8. selenium,webdriver模仿浏览器访问百度 基础1

    这是一种比较好的反反爬技术 #安装:pip install selenium=2.48.0 #显示:pip show selenium #卸载:pip uninstall selenium #模拟用户 ...

  9. mybatis关联查询之一对多查询

    一对多,是最常见的一种设计.就是 A 表的一条记录,对应 B 表的多条记录,且 A 的主键作为 B 表的外键.这主要看以哪张表为中心,下面的测试数据中,从employee 表来看,一个员工对应一个部门 ...

  10. linux 部署系统通过SecureCRT启动tomcat 控制台中文乱码

    查资料又是查了半天 首先 查看linux 当前系统字符集命令 echo $LANG 查看linux 当前系统语言 locale 网上说的又是下中文包,又是改临时语言,这些不能一概而论,我也觉得我不是中 ...