Net Core 2 Equivalent of HandleErrorAttribute

7.6k Views Asked by At

I am migrating .Net 4.6.2 project to Net Core 2.

What is the equivalent of HandleErrorAttribute ? Receiving Error below 2nd line

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new CustomerAuthorize());
    filters.Add(new HandleErrorAttribute()); 
}

Error:

The type or namespace name 'HandleErrorAttribute' could not be found (are you missing a using directive or an assembly reference?
1

There are 1 best solutions below

2
Ryan On

In asp.net core, you could use Exception Filters.

We could create a custom Exception Filter like:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
....
....

public class HandleExceptionAttribute : ExceptionFilterAttribute
{
 public override void OnException(ExceptionContext context)
 {
  var result = new ViewResult { ViewName = "Error" };
  var modelMetadata = new EmptyModelMetadataProvider();
  result.ViewData = new ViewDataDictionary(
          modelMetadata, context.ModelState);
  result.ViewData.Add("HandleException", 
          context.Exception);
  context.Result = result;
  context.ExceptionHandled = true;
 }           
}

A filter can be added to the pipeline at one of three scopes. You can add a filter to a particular action method or to a controller class by using an attribute. Or you can register a filter globally for all controllers and actions. Filters are added globally by adding it to the MvcOptions.Filters collection in ConfigureServices:

 services.AddMvc(options=>options.Filters.Add(new HandleExceptionAttribute()));

Refer to Create Custom Exception Filter In ASP.NET Core.