Add global exception handling middleware
Introduced `ExceptionHandlingMiddleware` to handle exceptions globally in the application. The middleware captures exceptions thrown during the request pipeline, logs them, and returns appropriate HTTP responses in JSON format. Key features: - Handles `JobException` with a 400 Bad Request response. - Handles unhandled exceptions with a 500 Internal Server Error. - Logs warnings for `JobException` and errors for unhandled exceptions. - Sets response `ContentType` to `application/json` and writes error details as JSON. Added necessary `using` directives for required namespaces.
This commit is contained in:
@@ -0,0 +1,74 @@
|
|||||||
|
using ECMJobRunner.Application.Common.Exceptions;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.Net;
|
||||||
|
|
||||||
|
namespace ECMJobRunner.WebCron.Middleware;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Middleware for handling exceptions globally in the application.
|
||||||
|
/// Captures exceptions thrown during the request pipeline execution,
|
||||||
|
/// logs them, and returns an appropriate HTTP response with a JSON error details.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Initializes a new instance of the <see cref="ExceptionHandlingMiddleware"/> class.
|
||||||
|
/// </remarks>
|
||||||
|
/// <param name="Next">The next middleware in the request pipeline.</param>
|
||||||
|
/// <param name="Logger">The logger instance for logging exceptions.</param>
|
||||||
|
public class ExceptionHandlingMiddleware(RequestDelegate Next, ILogger<ExceptionHandlingMiddleware> Logger)
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Invokes the middleware to handle the HTTP request.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context">The HTTP context of the current request.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
public async Task InvokeAsync(HttpContext context)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Next(context); // Continue down the pipeline
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
await HandleExceptionAsync(context, ex, Logger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Handles exceptions by logging them and writing an appropriate JSON response.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="context">The HTTP context of the current request.</param>
|
||||||
|
/// <param name="exception">The exception that occurred.</param>
|
||||||
|
/// <param name="logger">The logger instance for logging the exception.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger logger)
|
||||||
|
{
|
||||||
|
context.Response.ContentType = "application/json";
|
||||||
|
|
||||||
|
ValidationProblemDetails details;
|
||||||
|
|
||||||
|
switch (exception)
|
||||||
|
{
|
||||||
|
case JobException jobEx:
|
||||||
|
logger.LogWarning(jobEx, "Job exception occurred.");
|
||||||
|
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
|
||||||
|
details = new()
|
||||||
|
{
|
||||||
|
Title = "Job Exception",
|
||||||
|
Detail = jobEx.Message
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
logger.LogError(exception, "Unhandled exception occurred.");
|
||||||
|
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
|
||||||
|
details = new()
|
||||||
|
{
|
||||||
|
Title = "Internal Server Error",
|
||||||
|
Detail = "An unexpected error occurred. Please try again later."
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (details is not null)
|
||||||
|
await context.Response.WriteAsJsonAsync(details);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user