Handling and displaying runtime exception message to the user

(ASP.NET MVC)


Hi,
In this article i discuss about how to handle run time exception occurred in the asp.net mvc framework. In the view call the exception handling view and pass the exception viewdata, if any error occurred the exception view will display the error message in jquery ui dialog.

Views:-

@{
    ViewBag.Title = "exchandlingExample";
}

<h2>Exception Handling Demo</h2>

<script type="text/javascript">
      @Html.Partial(@"~/Views/ExceptionView/ExceptionHandling.cshtml", this.ViewData)
</script>

ExceptionHandling.cshtml

@if (Convert.ToString(ViewData["Exception"]) != null)
{
    Exception exc = (Exception)ViewData["Exception"];
       
        if(exc != null)
        {


    string exceptionType = exc.GetType().ToString();
    string exceptionMessage = exc.Message;
   

    <text>
    var str;
    var str2;
    str = @Html.Raw(Json.Encode(@exceptionType));
          str2 = @Html.Raw(Json.Encode(@exceptionMessage));
    var customerrorMsg = "<h1>Runtime Application Error</h1>" +
        "<h2>Exception Logged</h2>"+
        "<h3>Exception Type:- </h3>" + str +
        "<h3>Exception Message:- </h3>" + str2;
    customdialogExc("DivideByZeroException",customerrorMsg);
    </text>
    }
}




    function customdialogExc(headerValue, message) {

        //remove the existing div
        var divs = $('body').find('div[id="div_customdialogExc"]');

        $.each(divs, function (index, divItem) {
            $(divItem).remove();
        });

        //add new div
        $('body').append('<div id="div_customdialogExc"></div>');

        $('#div_customdialogExc').html(message);

        $('#div_customdialogExc').dialog({
            draggable: true,
            modal: true,
            resizable: true,
            width: 'auto',
            title: headerValue,
            minHeight: 75,
            buttons: {
                OK: function () {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                }
            }
        });

        $('#div_customdialogExc').dialog('open');
    }


Action Method:-

      //Exception Handling in asp.net mvc
        public ActionResult exchandlingExample()
        {
            try
            {
                int a = 2, b = 0;

                int result = a / b;

                return View();
            }
            catch (Exception exc)
            {
                ViewData["Exception"] = exc;

                return View();
            }
        }



Image

Ratings


Average Rating: 5.00 by 1 users
Giri Prasad
10/10/2013
10/10/2013
Download PDF

Comments






Sharma

Very useful