Error Handler In ASP.NET MVC

We are developers, who regularly fight with errors. Generally in .NET we are using try catch block for exception handling. But in ASP.NET MVC, we have some more features. Today in this article, I am going to show you how to handle error in ASP.NET MVC.

Follow these steps:

Step 1: Open Visual Studio, go to File, New, then Project and select ASP.NET MVC Web Application.

Step 2: Select Internet Application and click OK.

Internet Application

process

Open HomeController.cs

Add the following code:

  1. public ActionResult Index()  
  2. {  
  3.    throw new Exception("Error occured");  
  4. }  
When you run this code, you will get the following screen:

Exception

So above screen is just a normal error screen.

Now do one thing, open web.config and add <customerror mode=“on”>.
  1. <customErrors mode="On">  
  2.   
  3. </customErrors>  
When we create a new MVC Internet app, check your view folder, Shared Foldere, then error.cshtml.

This is the default page for error. Now add a [HandleError] attribute in action method.
  1. [HandleError]  
  2. public ActionResult Index()  
  3. {  
  4.    throw new Exception("Error occurred");  
  5. }  
Now run the page, you will get the following screen.

Run the page

Sometimes, we are getting 404 page not found error. Page not found error means, this particular page which user request for is not available on the server. For example, if we send a request for a different action method page, which is not available in the server, so let's see what will happen. Here's the screenshot:

error

So, what you see is HTTP 404. Because we don’t have any mypage action method exist in Home controller. So what about these type of errors.

 

  • Create a new controller as ErrorController.

  • Create a new action method as PageNotFound.
    1. public ActionResult PageNotFound()  
    2. {  
    3.    return View();  
    4. }  
  • Add a view for PageNotFound. Add whatever message you want to show for the user. Now do one more thing, open web.config and add some attributes in <customerror>.
    1. <customErrors mode="On">  
    2.    <error statusCode="404" redirect="~/Error/PageNotFound"/>  
    3. </customErrors>  

Now run the page which is not available on the server, and check the following screen. You are getting a message from ErrorController.

run

That’s it. I hope you enjoyed this article. If you have any query please write your comment, I’ll answer your queries.


Similar Articles