diff --git a/Program.cs b/Program.cs index 7221288..5fa9a9c 100644 --- a/Program.cs +++ b/Program.cs @@ -191,22 +191,21 @@ else // 로컬 테스트 위한 부분 (올릴떄는 켜두기) app.UseHttpsRedirection(); +//예외처리 미들웨어 부분 +app.UseMiddleware(); // 헤더 미들웨어 부분 -app.UseMiddleware((object)new string[] { "iOS_AM_Connect_Key", "And_AM_Connect_Key", "Web_AM_Connect_Key" }); -// app.UseMiddleware(); -// app.UseMiddleware("X-MyHeader"); - +app.UseMiddleware( + (object)new string[] { "iOS_AM_Connect_Key", "And_AM_Connect_Key", "Web_AM_Connect_Key" } + ); app.UseRouting(); -// app.MapControllers(); - app.UseCors("CorsPolicy"); app.UseAuthorization(); app.UseWebSockets(); app.UseEndpoints(end => { - end.MapControllers(); + ControllerEndpointRouteBuilderExtensions.MapControllers(end); end.MapHub("/chatHub"); }); diff --git a/Program/Common/Middleware/ExceptionMiddleware.cs b/Program/Common/Middleware/ExceptionMiddleware.cs index f373d31..e1b1d58 100644 --- a/Program/Common/Middleware/ExceptionMiddleware.cs +++ b/Program/Common/Middleware/ExceptionMiddleware.cs @@ -4,47 +4,46 @@ using Microsoft.Extensions.Logging; using System.Threading.Tasks; using Back.Program.Common.Model; -namespace Back.Program.Common.Middleware +namespace Back.Program.Common.Middleware; + +public class ExceptionMiddleware { - public class ExceptionMiddleware + private readonly RequestDelegate _next; + private readonly ILogger _logger; + + public ExceptionMiddleware(RequestDelegate next, ILogger logger) { - private readonly RequestDelegate _next; - private readonly ILogger _logger; + _next = next; + _logger = logger; + } - public ExceptionMiddleware(RequestDelegate next, ILogger logger) + public async Task Invoke(HttpContext context) + { + try { - _next = next; - _logger = logger; + 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(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; - // public async Task Invoke(HttpContext context) - // { - // try - // { - // await _next(context); // 다음 미들웨어 호출 - // } - // catch (AcaException ex) - // { - // _logger.LogWarning(ex, "AcaException 발생"); - // context.Response.StatusCode = 400; - // - // var response = APIResponse.Send(ex.Code, ex.Message, ""); - // var json = JsonSerializer.Serialize(response); - // - // context.Response.ContentType = "application/json; charset=utf-8"; - // 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); - // } - // } + var response = APIResponse.InternalSeverError("서버 내부 오류가 발생했습니다."); + var json = JsonSerializer.Serialize(response); + + context.Response.ContentType = "application/json; charset=utf-8"; + await context.Response.WriteAsync(json); + } } } \ No newline at end of file diff --git a/Program/Common/Model/AcaException.cs b/Program/Common/Model/AcaException.cs index 918de6e..a6d069d 100644 --- a/Program/Common/Model/AcaException.cs +++ b/Program/Common/Model/AcaException.cs @@ -1,74 +1,25 @@ -namespace Back.Program.Common.Model +using System.ComponentModel; + +namespace Back.Program.Common.Model; + +public static class ResposeCode { - /// - /// 입력 받은 토큰들(Access & Refresh) 자체에 문제가 있는 경우 - /// - public class TokenException: Exception - { - public TokenException(string message) : base(message) - { - } - } + public const string Success = "000"; + public const string InputErr = "100"; + public const string OutputErr = "200"; + public const string NetworkErr = "300"; + public const string UnknownErr = "999"; +} +public class AcaException : Exception +{ + public string Code { get; } + public int HttpStatus { get; } - /// - /// 리프레시 토큰이 만료가 나있는 경우 - /// - public class RefreshRevokeException: Exception + public AcaException(string code, string message, int httpStatus = 400) : base(message) { - public RefreshRevokeException(string message) : base(message) - { - } + this.Code = code; + this.HttpStatus = httpStatus; } +} - /// - /// 참조해야 하는 파일에서 오류가 발생하는 경우 - /// - public class FileNotValidException : Exception - { - public FileNotValidException(string message) : base(message) - { - } - } - /// - /// 파일 내부에 값을 읽을 때 오류가 발생하는 경우 - /// - public class FileContentNotFoundException : Exception - { - public FileContentNotFoundException(string message) : base(message) - { - } - } - - /// - /// 외부 서비스에 연결시 연결 실패시 - /// - public class ServiceConnectionFailedException : Exception - { - public ServiceConnectionFailedException(string message) : base(message) - { - - } - } - - /// - /// PUSH 서비스 중 데이터 사용에 문제가 발생했을시 - /// - public class PushInvalidException : Exception - { - public PushInvalidException(string message) : base(message) - { - - } - } - /// - /// 값이 있어야 하는데 NULL인 경우 - /// - public class OutNULLException : Exception - { - public OutNULLException(string message) : base(message) - { - - } - } -} \ No newline at end of file diff --git a/Program/Services/V1/PushService.cs b/Program/Services/V1/PushService.cs index ed7e257..9177b7d 100644 --- a/Program/Services/V1/PushService.cs +++ b/Program/Services/V1/PushService.cs @@ -75,8 +75,7 @@ namespace Back.Program.Services.V1 if (!response.IsSuccessStatusCode) { var errorContent = await response.Content.ReadAsStringAsync(); - throw new ServiceConnectionFailedException($"[푸시] : APNS 통신 실패 - {errorContent}"); - + throw new AcaException(ResposeCode.NetworkErr, $"[푸시] : APNS 통신 실패 - {errorContent}"); } } catch (Exception ex) diff --git a/Program/Services/V1/RepositoryService.cs b/Program/Services/V1/RepositoryService.cs index 07fbaef..9313c4a 100644 --- a/Program/Services/V1/RepositoryService.cs +++ b/Program/Services/V1/RepositoryService.cs @@ -223,8 +223,8 @@ namespace Back.Program.Services.V1 public string ReadSummary(Type type, string name) { - var method = type.GetMethod(name) ?? throw new OutNULLException("swagger summary Load ERROR: NULL"); - var att = method.GetCustomAttribute() ?? throw new OutNULLException("swagger summary Load ERROR: NULL"); + var method = type.GetMethod(name) ?? throw new AcaException(ResposeCode.NetworkErr,"swagger summary Load ERROR: NULL"); + var att = method.GetCustomAttribute() ?? throw new AcaException(ResposeCode.NetworkErr,"swagger summary Load ERROR: NULL"); return att.Summary; } }