WebTrainingRoom Online Courses
Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Exception handling in ASP.NET MVC

Exception handling implementation in Asp.net MVC is one of the important tasks in Application development;

Exception can occur for various reasons; here is few reasons that cause an exception.

  • Wrong input either from user or from other program
  • Wrong data type or casting
  • More data length than accepted or specified
  • Other dependent service failure
  • Disconcertion with database server due any reason
  • Bad coding, where some logical flow was not considered
Keywords used in Exception handling implementation
Try We write code inside the try block that may potentially throw an exception.
Catch Inside catch block codes written for handling the exception, so the exception does not terminate the application, also this is the place where we can call all type of error logging methods
Throw Using throw keyword we can throw the current exception or can throw a new exception with custom message
Finally Most of the developer don’t write this finally block, this block is always executed whether any exception occur or not, so if you need anything to be executed at last, this is the place to call the method

Here we see all best practice in error handing with example.

Different ways of Exception handling in Asp.Net MVC

Exception handling using try catch

Common way error handling exception is using try catch in your method or function

public ActionResult errorhandling()
{
try { // here is your functional coding, database call etc.
} catch (Exception ex) { // if anything goes wrong } finally { } return View(); }

Global Error handling in Asp.net MVC

We can implement error handling in Global.Asax, just by writing few lines code in Application_Error

protected void Application_Error(object sender, EventArgs e)              
{
    Exception exception = Server.GetLastError();
    // Here you can log / email exception details
    Server.ClearError(); // clear error & redirect to a common page
    Response.Redirect("CommonErrorPage");
}

Handling HTTP errors in Asp.net MVC
Implement error handling in web.Config, just by coniguring "customErrors" tag

 <system.web> <customErrors mode="On" defaultRedirect="CommonErrorPage">
<error statusCode="404" redirect="~/CommonErrorPage/NoPageFound"/>
</customErrors>
</system.web>
Exception Handing using "HandleErrorAttribute" in Asp.net MVC

HandleErrorAttribute class under System.Web.Mvc namespace

public class MyAppError : HandleErrorAttribute                 
{
    public override void OnException(ExceptionContext filterContext)
    {
        string _errorBaseInfo = null; 
        if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") 
        { 
            filterContext.Result = new JsonResult 
            { 
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new 
                { 
                    error = true, 
                    message = filterContext.Exception.Message 
                } 
            }; 
        _errorBaseInfo = filterContext.Exception.Message; 
        } 
    else 
    { 
        var controllerName = (string)filterContext.RouteData.Values["controller"]; 
        var actionName = (string)filterContext.RouteData.Values["action"]; 
        var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); 
                
        filterContext.Result = new ViewResult
        {
            ViewName = View,
            MasterName = Master,
            ViewData = new ViewDataDictionary(model),
            TempData = filterContext.Controller.TempData
        };               
        _errorBaseInfo = string.Format("controllerName={0} actionName={1} error={2}", controllerName, actionName, filterContext.Exception.Message);            
    }
                 
    LogError(filterContext.Exception.Message, filterContext.Exception);              
    filterContext.ExceptionHandled = true; 
    filterContext.HttpContext.Response.Clear(); 
    filterContext.HttpContext.Response.StatusCode = 500; 
    filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; 
    base.OnException(filterContext); 
} 
                 
    void LogError(string errorMessage, Exception ex)
    { 
        //ErrorDTO.TrackError(errorMessage, ex); 
    } 
}

Now you can use above attribute in any action like code below

    [MyAppError]              
    public ActionResult myTestView()
    {
    return View();
    } 
    
Exception handling using HandleError in Asp.Net MVC

Personally I don’t like this way of error handling, though it provide some built-in features like ArgumentOutOfRangeException , NotImplementedException etc

[HandleError]                     
public ActionResult Contact() 
{ 
    ViewBag.Message = "Your contact page."; 
    return View(); 
} 
                    
// We also can write with exception type                 
[HandleError(ExceptionType = typeof(ArgumentOutOfRangeException), View = "someDifferentView")]                  
[HandleError(ExceptionType = typeof(NotImplementedException), View = "myCommonError")]
public ActionResult Contact() 
{ 
    ViewBag.Message = "Your contact page."; 
    return View();
}
Error handling using Override "OnException" method in Asp.Net MVC

We also can Override “OnException” method in controller level , though not very attractive.

public class HomeController : Controller                    
{
    protected override void OnException(ExceptionContext filterContext)
    {
        Exception ex = filterContext.Exception;
        filterContext.ExceptionHandled = true;
                    
        var model = new HandleErrorInfo(filterContext.Exception, "myController", "myErrorPage");
                    
        filterContext.Result = new ViewResult() 
        { 
        ViewName = "Error", 
        ViewData = new ViewDataDictionary(model) 
        }; 
    } 
}

Hope you understood all different ways of exception handling in asp.net mvc application.

Comment
Name Email Website
Subscribe
 
Error handling in Asp.net MVC

Consulting