.NET Core- Ways to Manage Errors


Handling errors effectively in a .NET Core project is crucial for building robust and maintainable applications. Here are several ways to manage errors in a .NET Core project.

1. Global Exception Handling with Middleware

  • Use Exception Handling Middleware - Implement global error handling by creating a custom middleware that catches exceptions and processes them centrally.

  • Example

    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;
    
        public ExceptionHandlingMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, 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());
        }
    }
  • Register Middleware

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseMiddleware<ExceptionHandlingMiddleware>();
        // Other middlewares
    }

2. Use try-catch Blocks for Specific Operations

  • Fine-Grained Error Handling - Use try-catch blocks around operations that might fail, especially when interacting with external resources like databases, files, or APIs.
  • Example
    try
    {
        // Some code that might throw an exception
    }
    catch (SpecificException ex)
    {
        // Handle specific exception
    }
    catch (Exception ex)
    {
        // Handle general exceptions
    }

3. Use ILogger for Logging Errors

  • Log Exceptions - Ensure that all caught exceptions are logged using the ILogger service to aid in debugging and monitoring.
  • Example
    public class MyService
    {
        private readonly ILogger<MyService> _logger;
    
        public MyService(ILogger<MyService> logger)
        {
            _logger = logger;
        }
    
        public void DoWork()
        {
            try
            {
                // Some work that could fail
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An error occurred while doing work.");
                throw; // Re-throw if needed
            }
        }
    }

4. Use ProblemDetails for Consistent API Error Responses

  • Standardized Error Responses - For APIs, use ProblemDetails to provide consistent and meaningful error information to the client.
  • Example
    [ApiController]
    [Route("api/[controller]")]
    public class MyController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            try
            {
                // Some operation
            }
            catch (Exception ex)
            {
                var problemDetails = new ProblemDetails
                {
                    Status = StatusCodes.Status500InternalServerError,
                    Title = "An error occurred",
                    Detail = ex.Message
                };
                return StatusCode(StatusCodes.Status500InternalServerError, problemDetails);
            }
        }
    }

5. Custom Error Pages for UI Applications

  • Configure Custom Error Pages - For Razor Pages or MVC applications, configure custom error pages to provide a better user experience.
  • Example
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (!env.IsDevelopment())
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
        }
        // Other middlewares
    }

6. Handling Validation Errors

  • ModelState Validation -  Ensure that model validation errors are handled and returned correctly in APIs.
  • Example
    [HttpPost]
    public IActionResult Create([FromBody] MyModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        // Process the model
    }

Prev Next