Pages

Men

rh

10/20/2014

Error Handling Method 1: Day 1 of 23

Error handling using the HandleError() attribute at the action method level.

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 6Now 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 many kinds of errors generated through any page. So we create it under the shared folder.

Right-click on “Views”, select “Add” >> “New Folder”. 

add new item in view

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

Shared folder in view

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

Empty without model

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

Error

Step 10Design your desired custom error page in Error.cshtml.

desired custom error page

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

web config file

Step 12The Handle error attribute is used to handle an exception that is thrown by an action method. Apply the HandleError() attribute above the index action method and generate an exception inside the index action method. 

home controller

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

null reference error

Step 14Press "F5" and our custom error page is displayed.

custom error page
Source Collected from CSharpcorner.com
http://www.c-sharpcorner.com/UploadFile/db2972/error-handling-method-1-day-23-1-day-23/

No comments :

Post a Comment