Global Exception Handling in .NET 6

Exception handling is one of the important tasks in the application development cycle. Today, I am planning to tell you the effective way to handle the exceptions in the .Net 6. In that case, I’ll discuss,

  1. Exception Handling with Try-Catch Block

  2. Global Exception Handling with Custom MiddleWare


1. Exception Handling with Try-Catch Block

Try-Catch block is a basic approach to handle the exception, and let’s try it with the code example. I’ll use the ASP.NET Core Web API project based on the .Net 6.

using ExceptionHandling.Services;
using Microsoft.AspNetCore.Mvc;

namespace ExceptionHandling.Controllers;

public class UserController : Controller
{
    private readonly IUserService_userService;
    private readonly ILogger<UserController> _logger;
    
    public UserController
            (IUserService userService, ILogger<UserController> logger)    
    {
        _userService=userService;
        _logger=logger;    
    }    
    
    [HttpGet]
    public IActionResult GetUsers()    
    {
        try        
        {
            _logger.LogInformation("Getting Users details");
            
            var result =_userService.GetUsers();
            if (result == null)
                throw new ApplicationException("Getting Errors while 
                fetching users details");
            return Ok(result);        
        }
        catch (Exception e)        
        {
            _logger.LogError(e.Message);
            return BadRequest("Internal Server error");        
        }    
    }
}

Now, we have to check this one.

Response without exceptions