Others

Sunday, 13 May 2018

Handling Exception in Global.asax in MVC



Instead of writing the try and catch throughout the application, global.asax , application_error method is the common place to handle all the error and based on the type of exception it will redirect to the page.






Code snippet : For Gloab.asax page
·         Exception ex = Server.GetLastError();
It helps to get the last exception of the application that application find.

·         routeData.Values.Add("controller", "Error");
Registered the controller error for routing data.

·         Now here it is checking the types of error got in application as 401, 404 etc
             if (((HttpException)ex).GetHttpCode() == 404)
         {
                 routeData.Values.Add("action", "PageNotFound");
    }


·         Final code to execute the controller requert and redire t to particular controller and action.
errorController.Execute(new RequestContext(new HttpContextWrapper(Context),routeData));


protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();
            RouteData routeData = new RouteData();

            routeData.Values.Add("controller", "Error");

            Guid ErrorId = Guid.NewGuid();
            routeData.Values.Add("ErrorId", ErrorId);
            Response.Clear();


            if (ex is HttpException)
            {
                if (((HttpException)ex).GetHttpCode() == 404)
                {
                    routeData.Values.Add("action", "PageNotFound");
                }
                else if (((HttpException)ex).GetHttpCode() == 401)
                {
                    routeData.Values.Add("action", "UnAuthorized");
                }
                else
                {
                    routeData.Values.Add("ErrorValue", ex);
                    routeData.Values.Add("action", "Index");
                }
            }
            else if (ex is Exception)
            {
                routeData.Values.Add("ErrorValue", ex);
                routeData.Values.Add("action", "Index");
            }

            // LogHelper.ErrorLog(ErrorId.ToString(),ex);

            //Clear error in server
            Server.ClearError();

            Response.TrySkipIisCustomErrors = true;

            // Call the target controller and pass the route data
            IController errorController = new WebApplication2.Controllers.ErrorController();
            errorController.Execute(new RequestContext(new HttpContextWrapper(Context),routeData));
        }



Code snippet : For Error controller to get details in MVC

We will have three different action to handle three different type of error as 404, 401 and server error.

·         Code will use to get the exception detail in server side exception and which will use to display in DIV
Exception exception = this.RouteData.Values["ErrorValue"] != null ? (Exception)this.RouteData.Values["ErrorValue"] : null;

·         It converts the request type to html to display in the page.
Response.ContentType = "text/html";



public class ErrorController : Controller
    {
        // GET: Error
        public ActionResult Index()
        {
            Response.ContentType = "text/html";
            try
            {
                Exception exception = this.RouteData.Values["ErrorValue"] != null ? (Exception)this.RouteData.Values["ErrorValue"] : null;
                string errorId = this.RouteData.Values["ErrorId"].ToString();
                string message = exception != null ? exception.Message.ToString() : "Undefined Error";
                string stackTrace = exception.StackTrace.ToString();

                ViewBag.ErrorId = errorId;
                ViewBag.Message = message;
                ViewBag.StackTrace = stackTrace;
            }
            catch (Exception ex)
            {
                Guid ErrorId = Guid.NewGuid();
                ViewBag.ErrorId = ErrorId;
                ViewBag.Message = ex.Message.ToString();
                ViewBag.StackTrace = ex.StackTrace.ToString();
                // LogHelper.ErrorLog(ErrorId.ToString(),ex);
            }
            return View();
        }

        public ActionResult PageNotFound()
        {
            Response.ContentType = "text/html";
            return View();
        }

        public ActionResult UnAuthorized()
        {
            Response.ContentType = "text/html";
            return View();
        }
    }



Code snippet : For Server side exceptions in MVC for Index.cshtml

·         It Use to hide and show the actual error from outside.

<a href="javascript:void(0)" onclick="ShowErrorDetail();" style="text-decoration:none">@ViewBag.ErrorId</a>

<div class="form-group">
    <div class="row">
        <div class="col-md-10 col-md-offset-1 headerText">
            Technical Fault
        </div>
    </div>
    <br /><br />
    <div class="col-lg-12 col-sm-12 col-md-12">
        <div class="form-group text-center">
            <div class="alert alert-info" style="font-size:14px;font-weight:bold;">
                Please retry the same operation again. If you are facing problem concistently please contact administrator with below Id.
                <br />
                <a href="javascript:void(0)" onclick="ShowErrorDetail();" style="text-decoration:none">@ViewBag.ErrorId</a>
            </div>
        </div>
    </div>
    <br />
    <div class="col-lg-12 col-sm-12 col-md-12">
        <div class="form-group text-center" id="ErrorDetail" style="display:none">
            <div class="alert alert-danger">
                <b>@ViewBag.Message</b>
                @ViewBag.StackTrace
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    function ShowErrorDetail()
    {
        $("#ErrorDetail").toggle();
    }

</script>
Onclicking the Unique Id it will look like below.


No comments:

Post a Comment