Email: Password:       Forgot Password 
    .netCodeSG
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.
 
TECHNOLOGIES:
 

MVC Handle Error And Log into Data Base

Article:
Viewed:  35 
Posted On:  9/23/2017 6:46:57 AM 
In MVC how we can handle error globally and log into Data Base? 

As per request from one of my follower I am writing this article, which will explain how we can handle Error in a MVC application.

In this article I am also going to explain that how we can log our exception message in our Data Base.

Below is my Data Base Table where all error will be log:

1.png

Image 1.

Script of this table is:

CREATE TABLE [dbo].[ErrorLogger](
          [Error_ID] [int] IDENTITY(1,1) NOT NULL,
          [Error_Message] [text] NULL,
          [Error_Message_Detail] [text] NULL,
          [Controller_Name] [varchar](50) NULL,
          [Error_Logged_Date] [datetime] NULL,
 CONSTRAINT [PK_ErrorLogger] PRIMARY KEY CLUSTERED
(
          [Error_ID] ASC
)WITH (PAD_INDEX  = OFF,
 STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
 
GO
 
SET ANSI_PADDING OFF
GO
 
ALTER TABLE [dbo].[ErrorLogger] ADD  CONSTRAINT [DF_ErrorLogger_Error_Logged_Date] 
DEFAULT (getdate()) FOR [Error_Logged_Date]
GO


Now Open visual Studio -> File -> New Project =>

2.png

Image 2.

3.png

Image 3.

Now Right click on Models => Add New Item=> ADO.NET Entity Data Model

4.png

Image 4.

5.png

Image 5.

6.png

Image 6.

7.png

Image 7.

8.png

Image 8.

9.png

Image 9.

Now in your Solution Add a New Folder => CustomFilter

Here in this CustomFilter Folder add a new class => ExceptionHandlerAttribute.cs

 

10.png

Image 10.

Here in this class Add below code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LoggedExceptionInDB.Models;
 
namespace LoggedExceptionInDB.CustomFilter
{
    public class ExceptionHandlerAttribute: FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                ErrorLogger logger = new ErrorLogger()
                {
                    Error_Message = filterContext.Exception.Message,
                    Error_Message_Detail = filterContext.Exception.StackTrace,
                    Controller_Name = filterContext.RouteData.Values["controller"].ToString(),
                    Error_Logged_Date = DateTime.Now
                };
 
                RCompanyEntities ctx = new RCompanyEntities();
                ctx.ErrorLogger.Add(logger);
                ctx.SaveChanges();
                filterContext.ExceptionHandled = true;
            }
        }
    }
}

11.png

Image 11.

Now In App_Start add a new class => FilterConfig

Here add below code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LoggedExceptionInDB.CustomFilter;
using System.Web.Mvc;
 
namespace LoggedExceptionInDB.App_Start
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ExceptionHandlerAttribute());
        }
    }
}

12.png

Image 12.

Now in Global.asax write below line of code:

protected void Application_Start()
{
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
}


13.png

Image 13.

Now add a new controller => Controller =>

14.png

Image 14.

15.png

Image 15.

Here on Company Controller I am going to add a Method to insert new record like below:

Here above create method I am using   [ExceptionHandler]. Which will be responsible to log error in data base.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LoggedExceptionInDB.Models;
using LoggedExceptionInDB.CustomFilter;
 
namespace LoggedExceptionInDB.Controllers
{
    public class CompanyController : Controller
    {
        RCompanyEntities ctx = new RCompanyEntities();
 
        // GET: Company
        public ActionResult Index()
        {
            return View();
        }
 
        public ActionResult Create()
        {
            return View();
        }
 
        [ExceptionHandler]
        [HttpPost]
        public ActionResult Create(Company cmp)
        {
            int value;
            if (cmp.Country != "India")
            {
                throw new Exception("Add only Indian Company");
            }
            else if (!int.TryParse(cmp.ZipCode, out value))
            {
                throw new Exception("Zip Code only in Number");
            }
            else
            {
                //Logic To Add your Record.
 
            }
            return View(cmp);
        }
    }
}


16.png

Image 16.


Inside Models Folder I have added a class => Company

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace LoggedExceptionInDB.Models
{
    public class Company
    {        
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public string ZipCode { get; set; }
    }
}

CreateView.cshtml is:

@model LoggedExceptionInDB.Models.Company
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <h4>Company</h4>
        <hr />
        @Html.ValidationSummary(true""new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.City, ""new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Country, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Country, ""new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.ZipCode, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ZipCode, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ZipCode, ""new { @class = "text-danger" })
            </div>
        </div>
 
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Add New Company" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List""Index")
</div> 


Now Run you application:

If I enter any string value inside ZipCode then I am throwing exception:

17.png

Image 17.

18.png

Image 18.

Now check you data base table:

19.png

Image 19.

  Comment:
         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us