SPMS_API/SPMS.API/Middlewares/ExceptionMiddleware.cs

51 lines
1.6 KiB
C#

using SPMS.Domain.Common;
using SPMS.Domain.Exceptions;
namespace SPMS.API.Middlewares;
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 (SpmsException ex)
{
_logger.LogWarning(ex, "Business exception: {ErrorCode} {Message}", ex.ErrorCode, ex.Message);
await HandleSpmsExceptionAsync(context, ex);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception: {Message}", ex.Message);
await HandleUnknownExceptionAsync(context, ex);
}
}
private static async Task HandleSpmsExceptionAsync(HttpContext context, SpmsException exception)
{
context.Response.StatusCode = exception.HttpStatusCode;
context.Response.ContentType = "application/json";
var response = ApiResponse.Fail(exception.ErrorCode, exception.Message);
await context.Response.WriteAsJsonAsync(response);
}
private static async Task HandleUnknownExceptionAsync(HttpContext context, Exception exception)
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
var response = ApiResponse.Fail(ErrorCodes.InternalError, "서버 내부 오류가 발생했습니다.");
await context.Response.WriteAsJsonAsync(response);
}
}