Click here to Skip to main content
15,896,063 members
Articles / Web Development / ASP.NET
Tip/Trick

Error Handler In ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.33/5 (4 votes)
8 Nov 2015CPOL2 min read 11.8K   10  
In this tip, I am going to show you how to handle error in ASP.NET MVC.

Introduction

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

Using the Code

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.

Open HomeController.cs

Add the following code:

C++
public ActionResult Index()  
{  
   throw new Exception("Error occurred");  
} 

When you run this code, you will get the following screen:

So, the above screen is just a normal error screen.

Now do one thing, open web.config and add <customerror mode=“on”>.

C++
<customerror mode="on">

</customerror>

When we create a new MVC Internet app, check your view folder, Shared Folder, then error.cshtml.

This is the default page for error. Now add a [HandleError] attribute in action method.

C++
[HandleError]  
public ActionResult Index()  
{  
   throw new Exception("Error occurred");  
}  

Now run the page, you will get the following screen.

Sometimes, we are getting 404 page not found error. Page not found error means, this particular page which user requests 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:

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

  • Create a new controller as ErrorController.
  • Create a new action method as PageNotFound.
C++
public ActionResult PageNotFound()  
{  
   return View();  
}
  • 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>.
C++
<customErrors mode="On">  
   <error statusCode="404" redirect="~/Error/PageNotFound"/>  
</customErrors>    

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --