Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to handle errors in middleware C# Asp.net Core?
Create a new folder named CustomExceptionMiddleware and a class ExceptionMiddleware.cs inside it.
The first thing we need to do is to register our IloggerManager service and RequestDelegate through the dependency injection.
The _next parameter of RequestDeleagate type is a function delegate that can process our HTTP requests.
After the registration process, we need to create the InvokeAsync() method. RequestDelegate can’t process requests without it.
The _next delegate should process the request and the Get action from our controller should generate a successful response. But if a request is unsuccessful (and it is, because we are forcing exception),
our middleware will trigger the catch block and call the HandleExceptionAsync method.
public class ExceptionMiddleware{
private readonly RequestDelegate _next;
private readonly ILoggerManager _logger;
public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger){
_logger = logger;
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext){
try{
await _next(httpContext);
}
catch (Exception ex){
_logger.LogError($"Something went wrong: {ex}");
await HandleExceptionAsync(httpContext, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception exception){
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return context.Response.WriteAsync(new ErrorDetails(){
StatusCode = context.Response.StatusCode,
Message = "Internal Server Error from the custom middleware."
}.ToString());
}
}
Modify our ExceptionMiddlewareExtensions class with another static method −
public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder
app){
app.UseMiddleware<ExceptionMiddleware>();
}
use this method in the Configure method in the Startup class −
app.ConfigureCustomExceptionMiddleware();