Logging Exception in Database Using CustomFilter Exception

As per the request from one of my followers, I am writing this article which will explain how we can handle errors in an MVC application.

In this article, I am also going to explain how we can log our exception message in our Database.

Below is my Database Table where all the errors will be logged,

MVC

Script of this table is given below.

  1. CREATE TABLE [dbo].[ErrorLogger](  
  2.     [Error_ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Error_Message] [text] NULL,  
  4.     [Error_Message_Detail] [text] NULL,  
  5.     [Controller_Name] [varchar](50) NULL,  
  6.     [Error_Logged_Date] [datetime] NULL,  
  7.  CONSTRAINT [PK_ErrorLogger] PRIMARY KEY CLUSTERED   
  8. (  
  9.     [Error_ID] ASC  
  10. )WITH (PAD_INDEX  = OFF,  
  11.  STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,   
  12. ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  13. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  14.   
  15. GO  
  16.   
  17. SET ANSI_PADDING OFF  
  18. GO  
  19.   
  20. ALTER TABLE [dbo].[ErrorLogger] ADD  CONSTRAINT [DF_ErrorLogger_Error_Logged_Date]    
  21. DEFAULT (getdate()) FOR [Error_Logged_Date]  
  22. GO  

Now, open Visual Studio and go to File -> New Project.

MVC

MVC

Now eight click on Models => Add New Item=> ADO.NET Entity Data Model. Follow the process given in the pictures.

MVC

MVC

MVC

MVC

MVC

MVC

Now, in your Solution, add a new folder named CustomFilter. Here, in this CustomFilter folder, add a new class => ExceptionHandlerAttribute.cs.

MVC

Here, in this class, add the below code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using LoggedExceptionInDB.Models;  
  7.   
  8. namespace LoggedExceptionInDB.CustomFilter  
  9. {  
  10.     public class ExceptionHandlerAttribute: FilterAttribute, IExceptionFilter  
  11.     {  
  12.         public void OnException(ExceptionContext filterContext)  
  13.         {  
  14.             if (!filterContext.ExceptionHandled)  
  15.             {  
  16.                 ErrorLogger logger = new ErrorLogger()  
  17.                 {  
  18.                     Error_Message = filterContext.Exception.Message,  
  19.                     Error_Message_Detail = filterContext.Exception.StackTrace,  
  20.                     Controller_Name = filterContext.RouteData.Values["controller"].ToString(),  
  21.                     Error_Logged_Date = DateTime.Now  
  22.                 };  
  23.   
  24.                 RCompanyEntities ctx = new RCompanyEntities();  
  25.                 ctx.ErrorLogger.Add(logger);  
  26.                 ctx.SaveChanges();  
  27.                 filterContext.ExceptionHandled = true;  
  28.             }  
  29.         }  
  30.     }  
  31. }  

MVC

Now, in App_Start, add a new class as FilterConfig. Add the below code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using LoggedExceptionInDB.CustomFilter;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace LoggedExceptionInDB.App_Start  
  9. {  
  10.     public class FilterConfig  
  11.     {  
  12.         public static void RegisterGlobalFilters(GlobalFilterCollection filters)  
  13.         {  
  14.             filters.Add(new ExceptionHandlerAttribute());  
  15.         }  
  16.     }  
  17. }  

MVC

In Global.asax, write the below line of code.

  1. protected void Application_Start()  
  2.         {  
  3.             AreaRegistration.RegisterAllAreas();  
  4.             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  5.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  6.         }  

MVC

Now, add a new Controller.

MVC

MVC

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

Here, in the above created method I am using [ExceptionHandler] which will be responsible to log the error in the database.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using LoggedExceptionInDB.Models;  
  7. using LoggedExceptionInDB.CustomFilter;  
  8.   
  9. namespace LoggedExceptionInDB.Controllers  
  10. {  
  11.     public class CompanyController : Controller  
  12.     {  
  13.         RCompanyEntities ctx = new RCompanyEntities();  
  14.   
  15.         // GET: Company  
  16.         public ActionResult Index()  
  17.         {  
  18.             return View();  
  19.         }  
  20.   
  21.         public ActionResult Create()  
  22.         {  
  23.             return View();  
  24.         }  
  25.   
  26.         [ExceptionHandler]  
  27.         [HttpPost]  
  28.         public ActionResult Create(Company cmp)  
  29.         {  
  30.             int value;  
  31.             if (cmp.Country != "India")  
  32.             {  
  33.                 throw new Exception("Add only Indian Company");  
  34.             }  
  35.             else if (!int.TryParse(cmp.ZipCode, out value))  
  36.             {  
  37.                 throw new Exception("Zip Code only in Number");  
  38.             }  
  39.             else  
  40.             {  
  41.                 //Logic To Add your Record.  
  42.   
  43.             }  
  44.             return View(cmp);  
  45.         }  
  46.     }  
  47. }  

MVC

  1. @model LoggedExceptionInDB.Models.Company  
  2.   
  3. @{  
  4.     ViewBag.Title = "Create";  
  5. }  
  6.   
  7. <h2>Create</h2>  
  8.   
  9. @using (Html.BeginForm())   
  10. {  
  11.     @Html.AntiForgeryToken()  
  12.       
  13.     <div class="form-horizontal">  
  14.         <h4>Company</h4>  
  15.         <hr />  
  16.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  17.         <div class="form-group">  
  18.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  19.             <div class="col-md-10">  
  20.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  21.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })  
  22.             </div>  
  23.         </div>  
  24.   
  25.         <div class="form-group">  
  26.             @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })  
  27.             <div class="col-md-10">  
  28.                 @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })  
  29.                 @Html.ValidationMessageFor(model => model.City, ""new { @class = "text-danger" })  
  30.             </div>  
  31.         </div>  
  32.   
  33.         <div class="form-group">  
  34.             @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })  
  35.             <div class="col-md-10">  
  36.                 @Html.EditorFor(model => model.Country, new { htmlAttributes = new { @class = "form-control" } })  
  37.                 @Html.ValidationMessageFor(model => model.Country, ""new { @class = "text-danger" })  
  38.             </div>  
  39.         </div>  
  40.   
  41.         <div class="form-group">  
  42.             @Html.LabelFor(model => model.ZipCode, htmlAttributes: new { @class = "control-label col-md-2" })  
  43.             <div class="col-md-10">  
  44.                 @Html.EditorFor(model => model.ZipCode, new { htmlAttributes = new { @class = "form-control" } })  
  45.                 @Html.ValidationMessageFor(model => model.ZipCode, ""new { @class = "text-danger" })  
  46.             </div>  
  47.         </div>  
  48.   
  49.         <div class="form-group">  
  50.             <div class="col-md-offset-2 col-md-10">  
  51.                 <input type="submit" value="Add New Company" class="btn btn-default" />  
  52.             </div>  
  53.         </div>  
  54.     </div>  
  55. }  
  56.   
  57. <div>  
  58.     @Html.ActionLink("Back to List""Index")  
  59. </div>  

Inside Models folder, I have added a class named Company.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace LoggedExceptionInDB.Models  
  7. {  
  8.     public class Company  
  9.     {           
  10.         public string Name { get; set; }   
  11.         public string City { get; set; }  
  12.         public string Country { get; set; }  
  13.         public string ZipCode { get; set; }  
  14.     }  
  15. }  

Now, run your application. 

If I enter any string value inside ZipCode, then an exception is thrown.

MVC

MVC

Now, check your database table.

MVC


Similar Articles