6 Different ways to handle errors in MVC ( Including ajax)

6 Different ways to handle errors in MVC ( Including ajax)



Two ways to handle errors


1.  Redirection Rule – Redirect user to error page.

2. No Redirection Rule - Capture the error show the custom errors or actual error without redirecting. 



Redirection Rule


Method 1:- Simple way (using try catch)

#region Method1 - Try Catch
public ActionResult Method1()
{
try
{
throw new DivideByZeroException();
//return View();
}
catch (Exception ex)
{
return View("~/Views/AppError/Error.cshtml");
}
}
#endregion



Error.cshtml

@{
    ViewBag.Title = "Error";
}

<h2>Error</h2>




Method 2:- Override “OnException” method


#region Method 2 Overriding OnException
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)
};

}
public ActionResult Method2()
{
throw new Exception("I am Method 2 exception");
return View();
}
#endregion


if we are not able to find error view




it will take or call information given in webconfig. If it is present then it will take error.cshtml

    
Error.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Error</title>
</head>
<body>
    <hgroup>
        <h1>Error.1234</h1>
        <h2>An error occurred while processing your request.</h2>
        @Model.Exception;
    </hgroup>
</body>
</html>

<system.web>

<customErrors defaultRedirect="~/AppError/Index" mode="On">
      <error statusCode="404" redirect="~/AppError/HttpDenied"/></customErrors>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FailingGracefullyProj.Controllers
{
    public class AppErrorController : Controller
    {
        // GET: AppError
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult General()
        {
            string error = "";
            //return Content("Internal server error", "text/plain");
            //TempData["AppError"] = "Error : "+RouteData.Values["exception"];
            TempData["AppError"] = error;
            return View("General");
        }
        public ActionResult HttpDenied()
        {
            TempData["AppError"] = "HttpDenied";
            return View("General");
        }
        public ActionResult HttpSessionTimeout()
        {
            TempData["AppError"] = "Session time out";
            return View("General");
        }

        public ActionResult Error()
        {
            return View();
        }
    }
}
Index.cshtml

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div class="Inner_main-content">



    <div>
        <h2>Sorry, we can’t identify that page</h2>

        <p>Try our search bar or navigation at the top of the page.</p>
        <p>Possible reasons why we can’t find it:</p>
        <ul>
            <li>Check you entered the correct web address</li>
            <li>We may have removed or deleted the page</li>
        </ul>
        <p>Because we are scientists we’d like to solve this problem. Please help and report it to our<a href="#" title="404 error report mail">&nbsp;IT team</a>.</p>
    </div>

</div>







Method 3:- Using “HandleError” Attribute


#region Method 3 - HandleError Attritbute

        [HandleError]
        public ActionResult Method3()
        {
            throw new Exception("I am method 3 exception");
            return View();
        }
        #endregion
<system.web>
    <customErrors defaultRedirect="~/AppError/Index" mode="On">
      <error statusCode="404" redirect="~/AppError/HttpDenied"/>

    </customErrors>

It will first take Error.cshtml if not find then take the config.


Method 4:- Inheriting from “HandleErrorAttribute”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
//using System.Web.Http.ExceptionHandling;
using System.Web.Mvc;

namespace FailingGracefully.CustomAttribute
{
    public class HandleErrorsAttribute : HandleErrorAttribute
    {
        public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
        {
            {
                Exception ex = filterContext.Exception;
                filterContext.ExceptionHandled = true;
                var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");

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

    }
}

        #region Method 4:- Inheriting from “HandleErrorAttribute”

        [HandleErrors()]
        public ActionResult Method4()
        {
            throw new Exception("I am Method4 Exception");
            return View();
        }

        #endregion



No Redirection Rule


Method 5:- Adding error property to model

   #region Method 5 : TryCatch With custom error
        public ActionResult ModelError()
        {
            InformationModel model = new InformationModel()
            {
                Information1 = GetInformation1(),
                Information2 = GetInformation2(),
                Information3 = GetInformation3()
            };
            return View(model);
        }
        private Information GetInformation1()
        {
            Information information = new Information();
            try
            {
                information.InformationSource = "I am first";
            }
            catch (Exception ex)
            {
                information.Error_InformationSource = "I am first in trouble";
                // throw;
            }
            return information;
        }
        private Information GetInformation2()
        {
            Information information = new Information();
            try
            {
                throw new Exception("I am custom exception");
                information.InformationSource = "I am second";
            }
            catch (Exception ex)
            {
                information.Error_InformationSource = "I am second in trouble";
                // throw;
            }
            return information;
        }
        private Information GetInformation3()
        {
            Information information = new Information();
            try
            {
                information.InformationSource = "I am third";
            }
            catch (Exception ex)
            {
                information.Error_InformationSource = "I am third in trouble";
                // throw;
            }
            return information;
        }
        #endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FailingGracefullyProj.Models
{
    public class Information
    {
        public string InformationSource { get; set; }
        public string Error_InformationSource { get; set; }

    }
    public class InformationModel
    {
        public Information Information1 { get; set; }
        public Information Information2 { get; set; }
        public Information Information3 { get; set; }
    }

}

ModelError.cshtml
@model FailingGracefullyProj.Models.InformationModel

@{
    ViewBag.Title = "ModelError";
}

<h2>ModelError</h2>

<div>
    <h4>Information</h4>
    <hr />
    <d
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Information1.InformationSource)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Information1.InformationSource)
            <span class="error"> @Html.DisplayFor(model => model.Information1.Error_InformationSource)</span>
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Information2.InformationSource)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Information2.InformationSource)
            <span class="error"> @Html.DisplayFor(model => model.Information2.Error_InformationSource)</span>
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Information3.InformationSource)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Information3.InformationSource)
            <span class="error"> @Html.DisplayFor(model => model.Information3.Error_InformationSource)</span>
        </dd>
    </dl>
</div>

Method 6:- Override “OnException” method with Ajax request checking 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
//using System.Web.Http.ExceptionHandling;
using System.Web.Mvc;

namespace FailingGracefully.CustomAttribute
{
    public class HandleErrorsAttribute : HandleErrorAttribute
    {
        public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
            {
                //filterContext.HttpContext.Request.ContentType
                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                filterContext.Result = new JsonResult
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new
                    {
                        filterContext.Exception.Message,
                        filterContext.Exception.StackTrace
                    }
                };
                filterContext.ExceptionHandled = true;
            }
            else
            {
                Exception ex = filterContext.Exception;
                filterContext.ExceptionHandled = true;
                var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");

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

    }
}



 #region Method 6 : Ajax Error Handling
        public ActionResult HandleErrorAjax()
        {
            return View();
        }
        [HandleErrors]
        public ActionResult callMeIAmAJax()
        {
            InformationModel model = new InformationModel()
            {
                Information1 = GetInformation1(),
                Information2 = GetInformation2(),
                Information3 = GetInformation3()
            };
            throw new Exception("I am ajax excepion");
            return Json(model, JsonRequestBehavior.AllowGet);
        }
        #endregion
On Layout
    <script>
        var callMeIAmAJaxUrl = '@Url.Action("callMeIAmAJax", "Home")';
    </script>

HandleErrorAjax.cshtml

@{
    ViewBag.Title = "HandleErrorAjax";
}

<h2>HandleErrorAjax</h2>


<input id="CallMe" value="CallMe" type="button" />
<div id="showData">

    <div id="showError" style="color:red"></div>
</div>

@section scripts{
    <script>
        $('document').ready(function () {
            $('#CallMe').click(function () {
                //alert('Hello to myself');
                $.ajax({
                    type: "GET",
                    url: callMeIAmAJaxUrl,
                    data: param = "",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: successFunc,
                    error: errorFunc
                });
            });
        });
     function successFunc(data, status) {
        alert(data);
        //window.location.href = "@Url.Action("Index","Home")";

    }

        function errorFunc(request, status, error) {
            debugger;
            showErrorMessage("showError", JSON.parse(request.responseText).Message)
            //alert(JSON.parse(request.responseText).Message);
    }

    </script>
}







Share on Google Plus

About myzingonline

Myzingonline is all about zing to share experience, knowledge, likes, dislikes and ideas of a person to the world.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment