Click here to Skip to main content
15,886,110 members
Articles / Web Development / HTML

Exception Handling in MVC

Rate me:
Please Sign up or sign in to vote.
4.88/5 (11 votes)
17 Aug 2016CPOL2 min read 28.1K   369   36   7
Global level Exception Handling, Handle Exception using Try...Catch Block, HandleError attribute

Introduction

Let’s first establish what the purpose of code is in the first place.

For this article, the purpose of code is how to handle exceptions in MVC, different ways to handle exceptions in MVC and which way is the most suitable in which condition.

** Simple Approach by using Try...Catch Block **

It is the most basic level of Exception handling. Is is also called Method level exception handling.

What is Try Catch Block ?

The try block contains a block of code within which an exception might occur. Catch block will catch the exception which will occur in try block.

Syntax of Try...Catch:

C#
try
{
    //Your Code
}
catch(ExceptionType ObjectName)
{
    //Code for Handle Exception
}
C#
public ActionResult EXMethodApproch()
{
    try
    {
        //Generate Exception (NULL)
        object obj = null;
        string myStr = obj.ToString();

        //Generate Divide Zero Exception
        //int num = 0;
        //num /= num;

        return View();
    }
    catch(NullReferenceException)
    {
        return View("Your Custom Error Page");
    }
    catch(DivideByZeroException)
    {
        return View("Your Custom Error Page");
    }
}

If you use some External Dll / External Controls and you are not sure for its functionality, then you can use Method level (try...catch) exception handling.

The main disadvantage of using this method is that error handling login can't be reused.

** Global Level Exception Handling / "HandleError" Attribute **

What is HandleError Attribute?

HandleErrorAttribute is used to handle an exception which is thrown by ActionMethod and display friendly error pages when there is an unhandled exception.

  1. Add the below Action Method in Home controller:
    C#
    public ActionResult EXHandleErrorAttributeApproch()
    {
        throw new Exception("Error While Processing");
    }
    

    Run this page, we can find an exception as we did not handle exception in our code.

    Image 1

    Now, we understand how to display friendly error pages.

  2. Set [HandleError] Attribute on top of HomeController, for unhandled exceptions arising in any of its action methods are handled by it.

    Image 2

    Note: HandleError Attribute required customErrors mode="On" in your web.config File.

  3. Add FilterConfig.cs class in "App_Start" folder and Add "RegisterGlobalFilters" method as per below code.
    C#
    //Require Name Space: using System.Web.Mvc;
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
         filters.Add(new HandleErrorAttribute());
    }

    Image 3

  4. Now, set RegisterGlobalFilters method in Global.asax.cs file. Paste the below statement in Global.asax.cs file.
    C#
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    Image 4

  5. Enable Custom Error Mode in Web.config. Add the below code in your web.config:
    XML
    <customErrors mode="On">     
    </customErrors>

    After this, instead of silly yellow page, we just found two statement as below image:

    Image 5

  6. Run the project and enter a wrong URL. (Here, we enter wrong ActionResult name so 404 {The resource cannot be found} Exception Occurs)

    Image 6

  7. Add Error Page (for 404 Error Code):
    C#
    public ActionResult ErrorPage404()
    {
        return View();
    }

    Now, reference this page to customErrors in Web.config file.

    XML
    <customErrors mode="On">
         <error statusCode="404" redirect="~/Home/ErrorPage404"/>
    </customErrors>

    Run this page, and again go through step 6. Now we found the custom (friendly) error page.

    Image 7

** custom exception filter by extending HandleErrorAttribute class **

Add new class as "CustomErrorHandler", and paste the below code in that class.

C#
public class CustomErrorHandler : HandleErrorAttribute
{
    public override void OnException(ExceptionContext exceptionContext)
    {
        if (!exceptionContext.ExceptionHandled)
        {
            string controllerName = (string)exceptionContext.RouteData.Values["controller"];
            string actionName = (string)exceptionContext.RouteData.Values["action"];
            var model = new HandleErrorInfo(exceptionContext.Exception, controllerName, actionName);

            //This code shows the attribute where we redirect from Filter
            exceptionContext.Result = new ViewResult
            {
                ViewName = "ActionName of CustomError Page Name",
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = exceptionContext.Controller.TempData
            };
        }
    }
}

Now, add CustomErrorHandler to Filter Config:

C#
filters.Add(new CustomErrorHandler());

Image 8

So, we define our custom exception handler for handle exception.

Now just Add [CustomErrorHandler]  on top of your ActionResult Method or controller (if you want to apply in all ActionResult Method) .

[CustomErrorHandler]
public ActionResult TestCustomHandler()
{
    return View();
}

License

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



Comments and Discussions

 
PraiseGreat article. Pin
Nedyalko Dochev17-Jan-17 3:09
professionalNedyalko Dochev17-Jan-17 3:09 
GeneralMy vote of 5 Pin
Carsten V2.018-Aug-16 7:26
Carsten V2.018-Aug-16 7:26 
GeneralRe: My vote of 5 Pin
Khunt Suchit18-Aug-16 23:29
professionalKhunt Suchit18-Aug-16 23:29 
QuestionThe article is very detailed Pin
yaumo16-Aug-16 21:46
yaumo16-Aug-16 21:46 
AnswerRe: The article is very detailed Pin
Khunt Suchit17-Aug-16 0:14
professionalKhunt Suchit17-Aug-16 0:14 
GeneralUseful article Pin
Sachin Makwana16-Aug-16 20:02
professionalSachin Makwana16-Aug-16 20:02 
GeneralRe: Useful article Pin
Khunt Suchit16-Aug-16 21:25
professionalKhunt Suchit16-Aug-16 21:25 

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.