In this article, we will learn about how we can handle errors in ASP.NET.
Errors can occur during the development process in any application. At an early stage, it is important to be able to discover errors.
In ASP.Net, you can have custom error pages. A custom page will display the error to the user if an application contains any sort of error.
If the exception is not handled at any lower level, custom error pages can be displayed instead of a Yellow broken page.
Example
It can be defined at two levels:
- Application Level: In the Web.config file
- Page Level: At Page directive
1. Application Level: In the Web.config file
Create a new project and select the ASP.NET Empty Web Site.
Now, right-click the project name (CRUD Operations) in the Solution Explorer and select Add -> Add New Item.
First, add a new DefaultError.html file (Error Page), select HTML Page and click Add.
Open the DefaultError.html file and add the code in it.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Error</title> </head> <body> <h1>Something Went Wrong</h1> </body> </html>
Now, open Web.config file from Solution Explorer window and add the code in it as shown below.
<customErrors mode="On" defaultRedirect="DefaultError.html"></customErrors>
You can configure the following scenarios:
Example | Description |
---|---|
<customErrors mode=”Off” /> | A detailed status page is displayed to all users. |
<customErrors mode=”RemoteOnly” /> | A general status page is displayed to all users that request the site from other machines and a detailed page is displayed to all users that are requesting the page from the host server. |
<customErrors mode=”On” /> | A general page is displayed to all users. |
Now, let’s add a new Default.aspx file, right-click the project name (CRUD Operations) in the Solution Explorer and select Add -> Add New Item, select Web Form and click Add.
Open the Default.aspx.cs file and add the code in it.
This code generates System.NullReferenceException exception.
using System; using System.Collections.Generic; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { List<int> intList = null; int elem = intList[1]; } }
2. Page Level: At Page directive
We can set the custom error page at the page level also, using as below:
ErrorPage="DefaultError.html"
It will work especially for this page only.
Page-Level has the highest priority then application_error and then the Application Level custom in the Web.config file.
Note: In Web.config file customErrors mode must be On.
Output: