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.
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
}
try
{
// Some code that might throw an exception
}
catch (SpecificException ex)
{
// Handle specific exception
}
catch (Exception ex)
{
// Handle general exceptions
}
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
}
}
}
[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);
}
}
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (!env.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
}
// Other middlewares
}
[HttpPost]
public IActionResult Create([FromBody] MyModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Process the model
}