Created
May 30, 2021 16:14
-
-
Save manoj-choudhari-git/01b4b5bd23a21d25cfcdca3660d673e2 to your computer and use it in GitHub Desktop.
.NET Core Web API - Custom Exception Filter Attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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