Error Handling Method 5: Day 5 of 23

This article is about error handling and gettng exception details in a 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.ac.

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

Now we need to create a custom error page so that when an error occurrs, this custom error page is displayed. This error page is common for all kinds of errors generated through any page. So we create it under the shared folder. Right-click on “Views”, select “Add” >> “New Folder”.

Adding New Folder

Step 7

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

Creating Folder

Step 8

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

Adding View

Step 9

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

Creating View

Step 10

The @model directive provides a cleaner and more concise way to indicate to use strongly typed model classes within our view file. We just need to write @model and a strong model type at the top of view. Here in our example we use HandleErrorInfo with the @model directive. The HandleErrorInfo class encapsulates information for handling an error that was thrown by an action method.

View Code

Step 11

Open the web.config file, set customErrors mode=”On” under system.web. If you do not want to display a custom error page then you can set it to “Off”.

Web Configuration File

Step 12

Generate an exception inside the index action method.

Controller Code

Step 13

Now run the project and you will get a NullReferenceException since the session "temp" is not available.

NullReference Exception

Step 14

Press "F5" and it displays an error page with exception details like action name, controller name and exception message.

Error Page

<<Day 4 of 23

Up Next
    Ebook Download
    View all
    Learn
    View all