Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to handle errors in middleware C# Asp.net Core?
Error handling in ASP.NET Core middleware provides a centralized way to catch and process exceptions that occur during HTTP request processing. By creating custom exception middleware, you can standardize error responses and logging across your entire application.
Custom exception middleware intercepts exceptions before they reach the client, allowing you to log errors, format responses consistently, and hide sensitive internal details from users.
Creating Custom Exception Middleware
First, create a folder named CustomExceptionMiddleware and add a class ExceptionMiddleware.cs inside it. This middleware will handle all unhandled exceptions in your application −
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
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());
}
}
public class ErrorDetails
{
public int StatusCode { get; set; }
public string Message { get; set; }
public override string ToString()
{
return System.Text.Json.JsonSerializer.Serialize(this);
}
}
public interface ILoggerManager
{
void LogError(string message);
}
Key Components
The RequestDelegate _next parameter is a function delegate that processes HTTP requests in the pipeline. The InvokeAsync() method is required for RequestDelegate to process requests properly.
When a request is successful, the _next delegate processes it normally. However, if an exception occurs, the middleware catches it and calls HandleExceptionAsync to return a standardized error response.
Middleware Extension Method
Create an extension method to easily register your middleware in the application pipeline −
using Microsoft.AspNetCore.Builder;
public static class ExceptionMiddlewareExtensions
{
public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app)
{
app.UseMiddleware<ExceptionMiddleware>();
}
}
Registering the Middleware
In your Startup.cs or Program.cs file, register the middleware in the Configure method. Place it early in the pipeline to catch exceptions from subsequent middleware −
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.ConfigureCustomExceptionMiddleware();
// Other middleware registrations
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Complete Example with Controller
using Microsoft.AspNetCore.Mvc;
using System;
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
// This will trigger our exception middleware
throw new Exception("Test exception for middleware handling");
}
[HttpGet("success")]
public IActionResult GetSuccess()
{
return Ok(new { Message = "Request processed successfully" });
}
}
When you call the first endpoint, the middleware will catch the exception and return a standardized JSON error response with status code 500.
Enhanced Error Handling
You can enhance the middleware to handle different exception types with specific status codes and messages −
private Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
var response = new ErrorDetails();
switch (exception)
{
case ArgumentNullException:
response.StatusCode = (int)HttpStatusCode.BadRequest;
response.Message = "Invalid request parameter";
break;
case UnauthorizedAccessException:
response.StatusCode = (int)HttpStatusCode.Unauthorized;
response.Message = "Unauthorized access";
break;
default:
response.StatusCode = (int)HttpStatusCode.InternalServerError;
response.Message = "Internal Server Error";
break;
}
context.Response.StatusCode = response.StatusCode;
return context.Response.WriteAsync(response.ToString());
}
Conclusion
Custom exception middleware in ASP.NET Core provides centralized error handling, consistent error responses, and proper logging. By implementing this pattern, you ensure that all unhandled exceptions are caught and processed uniformly throughout your application, improving both user experience and debugging capabilities.
