You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.6 KiB
75 lines
2.6 KiB
7 days ago
|
using CoreAgent.Domain.Exceptions;
|
||
|
using CoreAgent.Domain.Models;
|
||
|
using Microsoft.AspNetCore.Http;
|
||
|
using Microsoft.Extensions.Logging;
|
||
|
using System.Net;
|
||
|
using System.Text.Json;
|
||
|
|
||
|
namespace CoreAgent.Infrastructure.Middleware
|
||
|
{
|
||
|
public class ExceptionMiddleware
|
||
|
{
|
||
|
private readonly RequestDelegate _next;
|
||
|
private readonly ILogger<ExceptionMiddleware> _logger;
|
||
|
|
||
|
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
|
||
|
{
|
||
|
_next = next;
|
||
|
_logger = logger;
|
||
|
}
|
||
|
|
||
|
public async Task InvokeAsync(HttpContext context)
|
||
|
{
|
||
|
try
|
||
|
{
|
||
|
await _next(context);
|
||
|
}
|
||
|
catch (Exception ex)
|
||
|
{
|
||
|
await HandleExceptionAsync(context, ex);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
|
||
|
{
|
||
|
var response = context.Response;
|
||
|
response.ContentType = "application/json";
|
||
|
|
||
|
var errorResponse = new ErrorResponse
|
||
|
{
|
||
|
TraceId = context.TraceIdentifier,
|
||
|
Message = "An error occurred while processing your request."
|
||
|
};
|
||
|
|
||
|
switch (exception)
|
||
|
{
|
||
|
case ValidationException validationEx:
|
||
|
response.StatusCode = (int)HttpStatusCode.BadRequest;
|
||
|
errorResponse.Message = validationEx.Message;
|
||
|
errorResponse.Errors = validationEx.Errors;
|
||
|
_logger.LogWarning("Validation error: {Message}", validationEx.Message);
|
||
|
break;
|
||
|
|
||
|
case NotFoundException notFoundEx:
|
||
|
response.StatusCode = (int)HttpStatusCode.NotFound;
|
||
|
errorResponse.Message = notFoundEx.Message;
|
||
|
_logger.LogWarning("Resource not found: {Message}", notFoundEx.Message);
|
||
|
break;
|
||
|
|
||
|
case UnauthorizedAccessException:
|
||
|
response.StatusCode = (int)HttpStatusCode.Unauthorized;
|
||
|
errorResponse.Message = "You are not authorized to access this resource.";
|
||
|
_logger.LogWarning("Unauthorized access attempt");
|
||
|
break;
|
||
|
|
||
|
default:
|
||
|
response.StatusCode = (int)HttpStatusCode.InternalServerError;
|
||
|
_logger.LogError(exception, "Unhandled exception occurred");
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
var result = JsonSerializer.Serialize(errorResponse);
|
||
|
await response.WriteAsync(result);
|
||
|
}
|
||
|
}
|
||
|
}
|