Wednesday, November 27, 2019

Custom Exception Filter in mvc


Custom Exception Filter in mvc

Custom Exception Filter in MVC

Exception filter is used to get errors at runtime or unhandled exceptions. we have to try-catch to handle the errors.
if you use try-catch at any action method then the exception filter won't work. but we can use in some cases like to handle some errors at the global level then we can use this filter. any class that inherits the IExceptionFilter then we call it as exception filter.

Note:
  1. Try-Catch block is used to handle the exception at runtime.
  2. Controller class Exceptions can be handled in different ways.
       try-catch to each action method of the Controller.
       Using the override OnException method
       Handling Run time errors at the global level using FilterConfig.cs class


Using Try-Catch clock in the Action method

public ActionResult  CreateATG()
{
    try
    {
         int  q = 100;  
        int  z = 0;  
        int k = q / z;  
        return RedirectToAction("Index");
    }
    catch(Exception ex)
    {
     return View("Error",new HandleErrorInfo(ex,"EmployeeInfo","home"));
    }
}


 Using the override OnException method

Step 1:

public class ATGExceptionFilter: FilterAttribute, IExceptionFilter  
  
  {  
    public override void OnException(ExceptionContext   atgfilterContext)
    {  
        Exception exp = atgfilterContext.Exception;
         //Logging the Exception
         atgfilterContext.ExceptionHandled = true;


   var Result = this.View("Error", new HandleErrorInfo(exp,
       atgfilterContext.RouteData.Values["controller"].ToString(),
       atgfilterContext.RouteData.Values["action"].ToString()));

   atgfilterContext.Result = Result;  
    }  


Step 2: Consuming the filter

[ATGExceptionFilter]  
public class HomeController: Controller 
{  
    public ActionResult  ATGIndex() {  
        int  q = 100;  
        int  z = 0;  
        int k = q / z;  
        return View();  
    }  
    public ActionResult  ATGAbout() {  
        ViewBag.Message = "ATG About page here.";  
        return View();  
    }  
    public ActionResult  ATGContact() {  
        ViewBag.Message = "ATG Contact Page";  
        return View();  
    }  



Using global level using FilterConfig.cs class

we need to declare at filterconfig class in App_Start folder.
it will be applicable at gobal level
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection  filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

No comments: