Error Handling Method 7

Error Handling Method 7

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.

6.png

Step 7

In order to create a custom error page, right-click on “Views”, select “Add” >> “New Folder”.

7.png

Step 8

Name the folder "Shared", this will create a "Shared" folder under the view.

8.png

Step 9

Right-click on the "Shared" folder and select "Add" >> "View…".

9.png

Step 10

Name the view "Error" and select "Empty (without model)" as the template.

10.png

Step 11

Inside error.cshtml, add a meaningful title to this page.

11.png

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.

12.png

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.

13.png

Step 14

Here you can see that it will jump to the OnException method.

14.png

Step 15

Now press F5 and you can see that custom error page is rendered in the browser.

15.png

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().

16.png

Step 17

To verify the step 16 comment the line where we set the value of ExceptionHandled to true inside the OnException method.

17.png

Step 18

Run the project in debug mode and the exception is thrown inside the Index action method.

18.png

Step 19

Continue debugging and it will jump to the OnException method. Here you can check the value of ExceptionHandled and it is false.

19.png

Step 20

Continue debugging and you will jump to Application_Error and here you get the exception details.

20.png

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.

21.png