Click here to Skip to main content
13,635,085 members
Click here to Skip to main content
Add your own
alternative version

Stats

301K views
102 bookmarked
Posted 4 Dec 2014
Licenced CPOL

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

, 4 Dec 2014
Rate this:
Please Sign up or sign in to vote.
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.

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.

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.

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:-

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

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.

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.

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.

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

License

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

Share

About the Author


You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralMessage Closed Pin
3-Jun-18 21:30
memberMember 138371233-Jun-18 21:30 
GeneralMessage Closed Pin
31-May-18 3:39
memberMember 1383712331-May-18 3:39 
QuestionGreat Article! Pin
Priyanka Kale11-Feb-18 20:24
memberPriyanka Kale11-Feb-18 20:24 
GeneralMethod 2 can be reused Pin
rprimora13-Sep-17 8:52
memberrprimora13-Sep-17 8:52 
Questionhow to use method 4 globally? Pin
Prabu ram23-Feb-17 20:42
memberPrabu ram23-Feb-17 20:42 
GeneralMy vote of 5 Pin
Boltyk15-Sep-16 12:10
memberBoltyk15-Sep-16 12:10 
Questiongood patterns Pin
kiquenet.com4-Apr-16 12:25
memberkiquenet.com4-Apr-16 12:25 
AnswerRe: good patterns Pin
Pooja Dalvi13-Dec-17 21:07
memberPooja Dalvi13-Dec-17 21:07 
QuestionMethod #4 Pin
cmacholz19-Jan-16 10:38
membercmacholz19-Jan-16 10:38 
QuestionVery clear, very useful. Pin
zamkinos1-Dec-15 3:01
memberzamkinos1-Dec-15 3:01 
QuestionMy Vote of 5 Pin
Thorsten Bruning9-Jun-15 8:33
memberThorsten 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
memberBlake A Niemyjski11-Dec-14 2:23 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun10-Dec-14 17:45
memberHumayun Kabir Mamun10-Dec-14 17:45 
GeneralGreat article Pin
MehdiNaseri4-Dec-14 20:37
memberMehdiNaseri4-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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.180712.1 | Last Updated 5 Dec 2014
Article Copyright 2014 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid