Skip to main content

Custom Filter

  • Custom Filter
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An unexpected error occurred. Please try again later."),
ReasonPhrase = "Internal Server Error"
};

// You can customize the error response based on the exception type
if (context.Exception is NotImplementedException)
{
response.Content = new StringContent("The requested feature has not been implemented.");
response.ReasonPhrase = "Not Implemented";
response.StatusCode = HttpStatusCode.NotImplemented;
}

context.Response = response;
}
}

/* 2 passo*/


public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Other configuration code...

config.Filters.Add(new CustomExceptionFilterAttribute());
config.Services.Replace(typeof(IExceptionLogger), new CustomExceptionLogger());
}
}