Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created May 30, 2021 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/01b4b5bd23a21d25cfcdca3660d673e2 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/01b4b5bd23a21d25cfcdca3660d673e2 to your computer and use it in GitHub Desktop.
.NET Core Web API - Custom Exception Filter Attribute
// Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Code to apply ExceptionHandlingFilter
services.AddControllers(options =>
{
options.Filters.Add(typeof(CustomExceptionFilterAttribute));
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Some code to set request processing pipeline
}
}
// Custom implementation for Exception Filter
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly ILogger<CustomExceptionFilterAttribute> _logger;
public CustomExceptionFilterAttribute(ILogger<CustomExceptionFilterAttribute> logger)
{
_logger = logger;
}
public override void OnException(ExceptionContext context)
{
base.OnException(context);
// Some logic to handle specific exceptions
var errorMessage = context.Exception is ArgumentException
? "ArgumentException occurred"
: "Some unknown error occurred";
// Maybe, logging the exception
_logger.LogError(context.Exception, errorMessage);
// Returning response
context.Result = new BadRequestResult();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment