49 lines
1.7 KiB
C#
49 lines
1.7 KiB
C#
using System.Text.Json;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Logging;
|
|
using System.Threading.Tasks;
|
|
using Back.Program.Common.Model;
|
|
|
|
namespace Back.Program.Common.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 Invoke(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await _next(context); // 다음 미들웨어 호출
|
|
}
|
|
catch (AcaException ex)
|
|
{
|
|
_logger.LogWarning(ex, $"예외 발생 : {ex.Message}");
|
|
// 400 : 이건 개발자가 직접 던지는 비즈니스 로직에 대한 예외 == 클라이언트의 오류
|
|
context.Response.StatusCode = ex.HttpStatus;
|
|
context.Response.ContentType = "application/json; charset=utf-8";
|
|
|
|
var response = APIResponse.Send<string>(ex.Code, ex.Message, string.Empty);
|
|
var json = JsonSerializer.Serialize(response);
|
|
await context.Response.WriteAsync(json);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Unhandled Exception");
|
|
context.Response.StatusCode = 500;
|
|
|
|
var response = APIResponse.InternalSeverError("서버 내부 오류가 발생했습니다.");
|
|
var json = JsonSerializer.Serialize(response);
|
|
|
|
context.Response.ContentType = "application/json; charset=utf-8";
|
|
await context.Response.WriteAsync(json);
|
|
}
|
|
}
|
|
} |