Home > DeveloperSection > Forums > How to implement exception handling in mvc.
Ankit Singh

Total Post:341

Points:2389
Posted on    October-18-2015 10:42 PM

 .NET C#  Mvc4 
Ratings:


 1 Reply(s)
 350  View(s)
Rate this:
Can anyone please help me how to solve this problem.


aditya kumar Patel

Total Post:250

Points:1782
Posted on    October-18-2015 10:54 PM

1- Create Error Page

2- Write Some Code

 

@model System.Web.Mvc.HandleErrorInfo

@{

    ViewBag.Title = "Error";

    Layout = "~/Views/Shared/_Layout.cshtml";

}

<div class="col-md-12" id="Page">

    <h3 class="text-center home-heding"> Error exception handling </h3>

    <div class="row" id="productpage">

        <div class="col-md-12 col-lg-12 col-sm-12 col-xs-12 orderbtn-box">

            <div class="col-md-12 col-lg-12 col-sm-12 col-xs-12 home-container" id="ProductPage">

                <div class="col-md-12 col-lg-12 col-sm-12 col-xs-12 " style="margin-top: 20px;">

                    <h2 class="text-center">500</h2>

                </div>

                <div class="col-md-12 col-lg-12 col-sm-12 col-xs-12">

                    <h2 class="text-center">Sorry An Error Has Occurred.</h2>

                </div>

              

                <div class="col-md-12 col-lg-12 col-sm-12 col-xs-12">

                     <hr />

                    <h4 class=" text-center">

                    @Url.RequestContext.RouteData.Values["Message"].ToString()</h4>

                </div>

            </div>

        </div>

    </div>

</div>



using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace Myproject.Models

{

    public class ErrorHandling : HandleErrorAttribute, IExceptionFilter

    {

        void IExceptionFilter.OnException(ExceptionContext filterContext)

        {

            Exception e = filterContext.Exception;

            //Log Exception e

            filterContext.ExceptionHandled = true;

            filterContext.RouteData.Values.Add("Message", e.Message.ToString());

            filterContext.Result = new ViewResult()

            {

                ViewName = "Error"

            };

        }

    }

}

namespace Myproject.Controllers

{

    [ErrorHandling]

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

               int a = 0;

                int b=2;

                int c = b/a;

               return View();

        }

    }

}

 


Modified On Oct-18-2015 10:57:26 PM

Don't want to miss updates? Please click the below button!

Follow MindStick