HOW TO IMPLEMENT EXCEPTION HANDLING IN MVC.

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
C#  Mvc4 
 668  View(s)
Ratings:
Rate this:
Can anyone please help me how to solve this problem.
  1. aditya kumar Patel

    Post:254

    Points:1810
    Re: How to implement exception handling in mvc.

    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!