Click here to Skip to main content
15,886,055 members
Articles / Web Development / ASP.NET

Exception handling in ASP.NET MVC (6 methods explained)

Rate me:
Please Sign up or sign in to vote.
4.80/5 (55 votes)
4 Dec 2014CPOL4 min read 413.8K   104   17
In this article we have discuss 6 ways of handling exceptions in ASP.NET MVC.

Contents

Exception handling in ASP.NET MVC (6 methods explained)

Introduction

Method 1:- Simple way

Method 2:- Override “OnException” method

Method 3:- Using “HandleError” Attribute

Method 4:- Inheriting from “HandleErrorAttribute”

Method 5:- Handling HTTP errors

Method 6:- Global Error handling in MVC

What’s the best practice ?

Further reading

Exception handling in ASP.NET MVC (6 methods explained)

Introduction

In this ASP.NET MVC step by step article we have discuss 6 ways of handling exceptions in ASP.NET MVC.In this article we also talk about best practices of MVC exception handling.

Image 1

Method 1:- Simple way

The simplestwayis to use the traditional .NET exception handling style i.e. try and catch block. Now when exception happens catch block gets executed and it redirects to the error view.

But if we use this method then we will not be utilizing MVC exception mechanismproperly and completely. In the further sections we will discuss five important ways by which we can utilize MVC provided features for exception handling.

”html”
public ActionResult SomeError()
{
try
{}
catch(Exception ex)
{return View("Error");}
}

Method 2:- Override “OnException” method

In this method we can override the “OnException” event of the controller and set the “Result” to the view name. This view gets invoked when error occurs in this controller. In the below code you can see we have set the “Result” to a view named as “Error”.

We have also set the exception so that it can be displayed inside the view.

”html”
public class HomeController : Controller
 {
        protected override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;

     var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");

     filterContext.Result = new ViewResult()
{
                ViewName = "Error",
                ViewData = new ViewDataDictionary(model)
     };

        }
}

To display the above error in view we can use the below code:-

”html”
@Model.Exception;

The problem with this approach is we cannot reuse the error handling logic across multiple controllers.

Method 3:- Using “HandleError” Attribute

The other way of handling error is my using “HandleError” attribute. Implementing “HandleError” attribute is a two-step process:-

Step 1 :- We need to first decorate the action method with “HandleError” attribute as shown in the below code.

”html”
public class HomeController : Controller
 {
        [HandleError()]
        public ActionResult SomeError()
        {
            throw new Exception("test");
        }
}

Step 2:- In the “Web.config” file you need to add the “customErrors” tag and point to the “Error” view as shown in the below “Web.config” code snippet.

<system.web>
<customErrors defaultRedirect="Error.cshtml" mode="On">
</customErrors>
</system.web> 

In case you want different error views for different exception types you can decorate action method with multiple “HandleError” attribute point to multiple views as per exception types.

”html”
public class HomeController : Controller
{
        [HandleError(ExceptionType=typeof(ArithmeticException),View="Arthimetic")]
[HandleError(ExceptionType = typeof(NotImplementedException),View ="Error1")]
public ActionResult SomeError()
{
    
}
}

Method 4:- Inheriting from “HandleErrorAttribute”

One of the biggest drawbacks of all the previous method was reusability. Error handling logic cannot be reused across other controllers.

In order to reuse error handling logic across controller we can inherit from “HandleErrorAttribute”class anddecorate this class as attribute across controller.

”html”
public class Err : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
        {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;
var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");

            filterContext.Result = new ViewResult()
            {
                ViewName = "Error1",
                ViewData = new ViewDataDictionary(model)
            };
        }
    }

Method 5:- Handling HTTP errors

All MVC exception handling techniques discussed till now do not handle HTTP errors like file not found, HTTP 500 error’s etc. For that we need to make an entry of the error action and the error status code as shown in the below config file.

<system.web>
<customErrors
                  mode="On" defaultRedirect="Error1">
<error statusCode="404" redirect="~/Testing/NoPageFound"/>
</customErrors>
</system.web> 

Method 6:- Global Error handling in MVC

If you wish to do global error handling across your application you can override the “Application_Error” event and do a response.redirect from the global error event. So if the error handling is not done at the controller level it will get propagated to “Global.asax” file.

”html”
public class MvcApplication : System.Web.HttpApplication
{
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            Server.ClearError();
            Response.Redirect("/Home/Error");
        }
}

What’s the best practice ?

The best is combination of “Method 4” and “Method 6”. Create error handling classeswhich inherit from “HandleErrorAttribute” class and decorate them respectively on controllers and action methods. So this takes care of errors happening on controllers and actions.

As a safety enable Global error handling as a fallback for any unexpected and unhandled errors byusing “Application_Error” event as described in “Method 6”.

Further reading

Below are some great discussions on internet forums which can help you further strengthen your knowledge.

Want to start Learning ASP.NET MVC, start from the below video which will teach you MVC in 16 hours i.e. 2 days

Image 2

For further reading do watch the below interview preparation videos and step by step video series.

License

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


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
Questionexecution order of Exception handling in ASP.NET MVC Pin
margam3117-Mar-21 8:34
margam3117-Mar-21 8:34 
GeneralCO_E_SERVER_EXEC_FAILURE Error in Excel @ server Pin
Sanket414-Feb-19 19:37
Sanket414-Feb-19 19:37 
QuestionGreat Article! Pin
Priyanka Kale11-Feb-18 20:24
Priyanka Kale11-Feb-18 20:24 
GeneralMethod 2 can be reused Pin
rprimora13-Sep-17 8:52
rprimora13-Sep-17 8:52 
Questionhow to use method 4 globally? Pin
Prabu ram23-Feb-17 20:42
Prabu ram23-Feb-17 20:42 
GeneralMy vote of 5 Pin
Boltyk15-Sep-16 12:10
Boltyk15-Sep-16 12:10 
Questiongood patterns Pin
kiquenet.com4-Apr-16 12:25
professionalkiquenet.com4-Apr-16 12:25 
AnswerRe: good patterns Pin
Pooja Dalvi13-Dec-17 21:07
Pooja Dalvi13-Dec-17 21:07 
QuestionMethod #4 Pin
cmacholz19-Jan-16 10:38
cmacholz19-Jan-16 10:38 
QuestionVery clear, very useful. Pin
zamkinos1-Dec-15 3:01
zamkinos1-Dec-15 3:01 
QuestionMy Vote of 5 Pin
Thorsten Bruning9-Jun-15 8:33
Thorsten Bruning9-Jun-15 8:33 
GeneralMy vote of 5 Pin
Afzaal Ahmad Zeeshan5-Jun-15 9:58
professionalAfzaal Ahmad Zeeshan5-Jun-15 9:58 
QuestionExceptionless Integration Pin
Blake A Niemyjski11-Dec-14 2:23
Blake A Niemyjski11-Dec-14 2:23 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun10-Dec-14 17:45
Humayun Kabir Mamun10-Dec-14 17:45 
GeneralGreat article Pin
MehdiNaseri4-Dec-14 20:37
professionalMehdiNaseri4-Dec-14 20:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.