mError handling and override OnException method and display custom error page.
Step 1
Create a MVC project from the "Empty" template. Right-click on "Controllers" and select "Add" >> "Controller...".
Step 2
Select "MVC 5 Controller - Empty" to add an empty controller. Click on the "Add" button.
Step 3
Name the controller "HomeController". The Index() action result method will be added.
Step 4
To add a view, right-click on "Index" and select "Add View...".
Step 5
Name the view and select "Empty (without model)" as the template. Click on the "Add" button.
Step 6
Generate an exception inside the index action method.
Step 7
In order to create a custom error page, right-click on “Views”, select “Add” >> “New Folder”.
Step 8
Name the folder "Shared", this will create a "Shared" folder under the view.
Step 9
Right-click on the "Shared" folder and select "Add" >> "View…".
Step 10
Name the view "Error" and select "Empty (without model)" as the template.
Step 11
Inside error.cshtml, add a meaningful title to this page.
Step 12
Now override the OnException method. First check the value of ExceptionHandled, if it is true then just return, else create an object of viewResult and set the ViewName, in other words a custom error page, that we want to display when an exception occurs. Finally set the value of ExceptionHandled to true.
Step 13
Run the project in debug mode and it will throw an exception inside the Index action method. Now continue with debugging and it will jump to the OnException method.
Step 14
Here you can see that it will jump to the OnException method.
Step 15
Now press F5 and you can see that custom error page is rendered in the browser.
Step 16
Now a question may arise in your mind that what if we do not set ExceptionHandled to true. So if you do not set ExceptionHandled to true, then its value remains false and it will jump to the Application_Error method inside Global.asax.cs. Let's get the exception details inside Application_Error using Server.GetLastError().
Step 17
To verify the step 16 comment the line where we set the value of ExceptionHandled to true inside the OnException method.
Step 18
Run the project in debug mode and the exception is thrown inside the Index action method.
Step 19
Continue debugging and it will jump to the OnException method. Here you can check the value of ExceptionHandled and it is false.
Step 20
Continue debugging and you will jump to Application_Error and here you get the exception details.
Step 21
Now press F5 and a server error page is displayed. So if we do not set ExceptionHandled to true then the custom error page will not be rendered and it renders the error page.
<< Error Handling Method 6: Day 6 of 23