Pages

Men

rh

10/20/2014

Error Handling Method 2: Day 2 of 23

This article explains error handling using the HandleError() attribute at the controller level.

Step 1Create 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 3Name the controller "HomeController". The Index() action result method will be added.

Step 4To add a view, right-click on "Index" and select "Add View...".

Step 5Name 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 by any page. So we create it under the shared folder.

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

add new folder

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

shared folder

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

shared folder property

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

name the view as error

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

error cshtml

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

customerErrors mode

Step 12The Handle error attribute handles an exception thrown by an action method. Apply the HandleError() attribute above the home controller, it will work for all action methods of the home controller. Generate an exception inside the index action method. 

handleError

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

Null Reference Exception

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-2-day-2-of-23/

No comments :

Post a Comment