49 lines
1.6 KiB
C#
49 lines
1.6 KiB
C#
using System.Text.Json;
|
|
using General_Ledger_Service.DTOs.Common;
|
|
using General_Ledger_Service.Exceptions;
|
|
|
|
namespace General_Ledger_Service.Middleware
|
|
{
|
|
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)
|
|
{
|
|
var (statusCode, message) = ex switch
|
|
{
|
|
NotFoundException => (StatusCodes.Status404NotFound, ex.Message),
|
|
BadRequestException => (StatusCodes.Status400BadRequest, ex.Message),
|
|
UnauthorizedException => (StatusCodes.Status401Unauthorized, ex.Message),
|
|
ForbiddenException => (StatusCodes.Status403Forbidden, ex.Message),
|
|
_ => (StatusCodes.Status500InternalServerError, "An unexpected error occurred")
|
|
};
|
|
|
|
context.Response.StatusCode = statusCode;
|
|
context.Response.ContentType = "application/json";
|
|
|
|
var response = new ApiResponse
|
|
{
|
|
StatusCode = statusCode,
|
|
Success = false,
|
|
Message = message,
|
|
Data = null
|
|
};
|
|
|
|
await context.Response.WriteAsync(JsonSerializer.Serialize(response));
|
|
}
|
|
}
|
|
}
|
|
}
|