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 = ON) ON [PRIMARY]
  13. ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  14. GO
  15. SET ANSI_PADDING OFF
  16. GO
  17. ALTER TABLE [dbo].[ErrorLogger] ADD CONSTRAINT [DF_ErrorLogger_Error_Logged_Date]
  18. DEFAULT (getdate()) FOR [Error_Logged_Date]
  19. 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. namespace LoggedExceptionInDB.CustomFilter
  8. {
  9. public class ExceptionHandlerAttribute: FilterAttribute, IExceptionFilter
  10. {
  11. public void OnException(ExceptionContext filterContext)
  12. {
  13. if (!filterContext.ExceptionHandled)
  14. {
  15. ErrorLogger logger = new ErrorLogger()
  16. {
  17. Error_Message = filterContext.Exception.Message,
  18. Error_Message_Detail = filterContext.Exception.StackTrace,
  19. Controller_Name = filterContext.RouteData.Values["controller"].ToString(),
  20. Error_Logged_Date = DateTime.Now
  21. };
  22. RCompanyEntities ctx = new RCompanyEntities();
  23. ctx.ErrorLogger.Add(logger);
  24. ctx.SaveChanges();
  25. filterContext.ExceptionHandled = true;
  26. }
  27. }
  28. }
  29. }

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. namespace LoggedExceptionInDB.App_Start
  8. {
  9. public class FilterConfig
  10. {
  11. public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  12. {
  13. filters.Add(new ExceptionHandlerAttribute());
  14. }
  15. }
  16. }

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. namespace LoggedExceptionInDB.Controllers
  9. {
  10. public class CompanyController : Controller
  11. {
  12. RCompanyEntities ctx = new RCompanyEntities();
  13. // GET: Company
  14. public ActionResult Index()
  15. {
  16. return View();
  17. }
  18. public ActionResult Create()
  19. {
  20. return View();
  21. }
  22. [ExceptionHandler]
  23. [HttpPost]
  24. public ActionResult Create(Company cmp)
  25. {
  26. int value;
  27. if (cmp.Country != "India")
  28. {
  29. throw new Exception("Add only Indian Company");
  30. }
  31. else if (!int.TryParse(cmp.ZipCode, out value))
  32. {
  33. throw new Exception("Zip Code only in Number");
  34. }
  35. else
  36. {
  37. //Logic To Add your Record.
  38. }
  39. return View(cmp);
  40. }
  41. }
  42. }

MVC

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

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