Pages

Men

rh

10/20/2014

Error Handling Method 3: Day 3 of 23

This article describes error handling using global filters for all controllers.
To learn other error handling method, you can see following articles:
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 all 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 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…".

view option

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

Empty without model

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”.

custom error model

Step 12Generate an exception inside the index action method. 

home controller

Step 13Right-click on “App_Start”, select “Add” >> “Class…”.

add new controller

Step 14Select “Class” from the installed templates and provide an appropriate name like "ErrorConfig".

error coding

Step 15In the following code snippet you can see the static method that accepts a GlobalFilterCollection and adds our HandleErrorAttribute into the filter collection or we can say the register global filter. Without any additional modification in the controllers and their action methods we add a HandleErrorAttribute for all the controllers.

ErrorConfig

Step 16Now call this static method inside the Application_Start event of Global.asax.cs, so that it will be implemented as soon as the application starts.

registerFilter

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

null reference expectiona

Step 18Press "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-3-day-3-of-23691/

No comments :

Post a Comment