Global Exception Handling Using Exception filter attribute

 Global Exception  using Exception filter attribute in .net core

Audit log is the most important part of  a web application. In this article we will create log for user.

The article contains
  1.  Create Table
  2.  Store Procedure
  3.  Action filter attribute
  4.  Implementation in controller
  5. Add Transient in Startup.cs

Create Table

CREATE TABLE GlobalException (
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Error] [nvarchar](500) NULL,
	[Controller] [nvarchar](100) NULL,
	[Action] [nvarchar](100) NULL,
	[UserID] [int] NULL,
	[Created_Date] [datetime] NULL
)

Store Procedure

CREATE PROCEDURE usp_ErrorLog_Generation   
 @Error AS NVARCHAR(500)  
,@Controller AS NVARCHAR(100)  
,@Action AS NVARCHAR(100)  
,@UserID AS INT   
As   
BEGIN  
INSERT INTO GlobalException(Error,Controller,Action,UserID,BranchID,Created_Date) 
               VALUES(@Error,@Controller,@Action,@UserID,GETDATE())  
END 

Exception filter attribute

public class HandleExceptionAttribute : ExceptionFilterAttribute
{
    UnitOfWork dmsUnitOfWork = new UnitOfWork();
    public override void OnException(ExceptionContext context)
    {
        int userid = 0;
        var controller = context.RouteData.Values["controller"].ToString();
        var action = context.RouteData.Values["action"].ToString();
        var error = context.Exception.Message;
        if(context.HttpContext.Session.GetString("UserId") != null)
            userid = Convert.ToInt32(context.HttpContext.Session.GetString("UserId").ToString());

        var result = new ViewResult { ViewName = "Error" };
        var modelMetadata = new EmptyModelMetadataProvider();
        result.ViewData = new ViewDataDictionary(
                modelMetadata, context.ModelState);
        result.ViewData.Add("HandleException",
                context.Exception);
        
        dmsUnitOfWork.GetRepositoryInstance<object>().WriteStoredProcedure("usp_ErrorLog_Generation,@Error,@Controller,@Action,@UserID",
                ,new SqlParameter("Error", System.Data.SqlDbType.NVarChar) { Value = error }
                , new SqlParameter("Controller", System.Data.SqlDbType.NVarChar) { Value =controller }
                , new SqlParameter("Action", System.Data.SqlDbType.NVarChar) { Value = action }
                , new SqlParameter("UserID", System.Data.SqlDbType.Int) { Value = userid });
      
         context.Result = result;
        context.ExceptionHandled = true;
    }
}

Implementation in controller

[HandleException]
public class HomeController : Controller
{
      private readonly User _user;

      public HomeController(User user)
      {
          _user=user;
      }

      public ActionResult Index()
      {
          var users=_user.GetAll();
          return View(users);
      }
}

Add Transient in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
 services.AddTransient<HandleExceptionAttribute>();
}

Post a Comment

0 Comments