Implementation of Global Exception Handling using .NET Core 6 Web API

What is Global Exception Handling?

Global exception handling involves setting up a mechanism to catch exceptions that may occur during the processing of incoming requests. Instead of relying on individual try-catch blocks within each API endpoint.

Benefits of Global Exception Handling

1.Consistent Error Responses: Global exception handling ensures a uniform and consistent way to handle errors throughout your API. Clients can rely on a standardized error response format, making it easier for them to understand and handle errors.

2.Maintainability and DRY Principle: Centralizing exception handling logic in a middleware component promotes the Don’t Repeat Yourself (DRY) principle. You can manage exception-related code in one place, making it easier to maintain and reducing code duplication across your API.

3.Improved Code Readability: Separating error-handling logic from the main business logic of your API controllers results in cleaner and more readable code. The core logic of your API methods can focus on their primary responsibilities, while error handling is handled centrally.

4.Logging and Monitoring: Global exception handling allows you to log exceptions consistently, providing valuable information for debugging and monitoring. You can log exceptions, along with relevant details, to track issues and diagnose problems in your application.

5.Security: Properly handling exceptions helps improve the security of your web API by preventing the exposure of sensitive information to clients. You can control the level of detail in error responses and avoid exposing internal implementation details in production environments.

Implementation of Global Exception Handling

Step 1. Create a new .NET Core Web API Project.

Step 2. Install the following NuGet Packages.

Step 3. Final Project Structure.

Step 4. Create your model and then implement your service, interface and controller.

Step 5. Create multiple exception classes inside Exception.

Step 6. You can throw and catch this specific exception in your API controllers.

using AllGlobalExceptionHandling.WebApi.Exception;
using AllGlobalExceptionHandling.WebApi.Interface;
using AllGlobalExceptionHandling.WebApi.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace AllGlobalExceptionHandling.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly IProductService productService;
        private ILogger<ProductController> _logger;
        public ProductController(IProductService _productService, ILogger<ProductController> logger)
        {
            productService = _productService;
            _logger = logger;
        }
        [HttpGet("productlist")]
        public Task<IEnumerable<Product>> ProductList()
        {
            var productList = productService.GetProductList();
            return productList;
        }
        [HttpGet("getproductbyid")]
        public Task<Product> GetProductById(int Id)
        {
            _logger.LogInformation($"Fetch Product with ID: {Id} from the database");
            var product = productService.GetProductById(Id);
            if (product.Result == null)
            {
                throw new NotFoundException($"Product ID {Id} not found.");
            }
            _logger.LogInformation($"Returning product with ID: {product.Result.ProductId}.");
            return product;

        }
        [HttpPost("addproduct")]
        public Task<Product> AddProduct(Product product)
        {
            return productService.AddProduct(product);
        }
        [HttpPut("updateproduct")]
        public Task<Product> UpdateProduct(Product product)
        {
            return productService.UpdateProduct(product);
        }
        [HttpDelete("deleteproduct")]
        public Task<bool> DeleteProduct(int Id)
        {
            return productService.DeleteProduct(Id);
        }
        [HttpGet("filterproduct")]
        public Task<List<Product>> FilterProduct(int Id)
        {
            throw new System.NotImplementedException("Not Implemented Exception!");
        }
    }
}

Step 7. Create a GlobalErrorHandlingMiddleware inside Middleware folder to handle exceptions.

Step 8. Configure your middleware inside the program class..

Step 9. Finally, run your application.

Step 10. Here in the below images, you see exceptions when passing invalid product id or sometimes call unimplemented method. I took only these two examples, but there are many scenarios in which you use and handle the exception as per your need.

Hope this blog helps in Global Exception Handling

Related Blogs

Elevate ASP.NET Core Web API speed with caching. Explore in-memory, distributed, and