Exception Handling in .net core

 Global Middleware for Exception

  • Use custom middleware to catch and handle unhandled exceptions

  • Register middleware early in the pipeline (before routing)

  • Log exceptions and return a consistent error response (e.g., ProblemDetails format)

Example:


public class GlobalExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILogger<GlobalExceptionMiddleware> _logger; public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext context) { try { await _next(context); // Proceed to next middleware } catch (Exception ex) { _logger.LogError(ex, "Unhandled exception occurred."); context.Response.StatusCode = 500; context.Response.ContentType = "application/json"; var response = new { error = ex.Message, trace = ex.StackTrace }; await context.Response.WriteAsJsonAsync(response); } } }

Register in Program.cs:


app.UseMiddleware<GlobalExceptionMiddleware>();



1. What are the ways to handle exceptions in .NET Core?

  • Try-Catch blocks in service or controller methods
  • Exception filters (IExceptionFilter, ExceptionFilterAttribute) in MVC
  • Global exception handling via custom middleware
  • UseStatusCodePages for simple status code mapping
  • Use of ProblemDetails object for standard error responses

2. What’s the difference between middleware-based exception handling and exception filters?



Best Practice: Use middleware for global error handling and filters for controller-specific scenarios.


Write sample custom exception.

public class UserNotFoundException : Exception { public UserNotFoundException(int userId) : base($"User with ID {userId} was not found.") { } }


No comments:

Post a Comment

Pages