[♻️] APIResponse 리팩토링, Exception 세분화 진행

This commit is contained in:
김선규 2025-02-26 11:20:08 +09:00
parent 806541e4d7
commit 47f3b30010
6 changed files with 158 additions and 111 deletions

View File

@ -20,59 +20,103 @@ public class Status
} }
public static class DefaultResponse public static class APIResponse
{ {
// private static readonly Lazy<ErrorResponse> _instance = new Lazy<ErrorResponse>(); public static APIResponseStatus<T> Send<T>(string code, string message, T data)
// public static ErrorResponse Instace => _instance.Value; {
return new APIResponseStatus<T>
{
status = new Status()
{
code = code,
message = message
},
data = data
};
}
// private ErrorResponse() /// <summary>
/// 반환값 없는 API 정상 동작시
/// </summary>
public static APIResponseStatus<string> Success (){
return Send("000", "정상", "");
}
public static APIResponseStatus<string> InvalidInputError()
{
return Send("001", "입력 값이 유효하지 않습니다.", "");
}
public static APIResponseStatus<string> NotFoundError()
{
return Send("002", "알맞은 값을 찾을 수 없습니다.", "");
}
public static APIResponseStatus<string> InternalSeverError()
{
return Send("003", "통신에 오류가 발생하였습니다.", "");
}
public static APIResponseStatus<string> UnknownError()
{
return Send("999", "알 수 없는 오류가 발생하였습니다.", "");
}
}
//
// public static class DefaultResponse
// { // {
// // 외부 초기화 방지 // // private static readonly Lazy<ErrorResponse> _instance = new Lazy<ErrorResponse>();
// // public static ErrorResponse Instace => _instance.Value;
//
// // private ErrorResponse()
// // {
// // // 외부 초기화 방지
// // }
//
//
// public static APIResponseStatus<string> Success = new APIResponseStatus<string>
// {
// status = new Status()
// {
// code = "000",
// message = "정상"
// }
// };
//
// public static APIResponseStatus<string> InvalidInputError = new APIResponseStatus<string>
// {
// status = new Status()
// {
// code = "001",
// message = "입력 값이 유효하지 않습니다."
// }
// };
//
// public static APIResponseStatus<string> NotFoundError = new APIResponseStatus<string>
// {
// status = new Status()
// {
// code = "002",
// message = "알맞은 값을 찾을 수 없습니다."
// }
// };
//
// public static APIResponseStatus<string> InternalSeverError = new APIResponseStatus<string>
// {
// status = new Status
// {
// code = "003",
// message = "통신에 오류가 발생하였습니다."
// }
// };
//
//
// public static APIResponseStatus<string> UnknownError = new APIResponseStatus<string>
// {
// status = new Status()
// {
// code = "999",
// message = "알 수 없는 오류가 발생하였습니다."
// }
// };
// } // }
public static APIResponseStatus<string> Success = new APIResponseStatus<string>
{
status = new Status()
{
code = "000",
message = "정상"
}
};
public static APIResponseStatus<string> InvalidInputError = new APIResponseStatus<string>
{
status = new Status()
{
code = "001",
message = "입력 값이 유효하지 않습니다."
}
};
public static APIResponseStatus<string> NotFoundError = new APIResponseStatus<string>
{
status = new Status()
{
code = "002",
message = "알맞은 값을 찾을 수 없습니다."
}
};
public static APIResponseStatus<string> InternalSeverError = new APIResponseStatus<string>
{
status = new Status
{
code = "003",
message = "통신에 오류가 발생하였습니다."
}
};
public static APIResponseStatus<string> UnknownError = new APIResponseStatus<string>
{
status = new Status()
{
code = "999",
message = "알 수 없는 오류가 발생하였습니다.."
}
};
}

View File

@ -25,7 +25,7 @@ public class AppController : ControllerBase
{ {
if (string.IsNullOrEmpty(type)) if (string.IsNullOrEmpty(type))
{ {
return BadRequest(DefaultResponse.InvalidInputError); return BadRequest(APIResponse.InvalidInputError);
} }
try try
@ -34,7 +34,7 @@ public class AppController : ControllerBase
if (version == null) if (version == null)
{ {
return NotFound(DefaultResponse.NotFoundError); return NotFound(APIResponse.NotFoundError);
} }
var response = new APIResponseStatus<Version> var response = new APIResponseStatus<Version>
@ -62,7 +62,7 @@ public class AppController : ControllerBase
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"{ex.Message}\n{ex.StackTrace}"); Console.WriteLine($"{ex.Message}\n{ex.StackTrace}");
return StatusCode(500, DefaultResponse.UnknownError); return StatusCode(500, APIResponse.UnknownError);
} }
} }
} }

View File

@ -46,16 +46,16 @@ public class PushController : ControllerBase
if (string.IsNullOrWhiteSpace(deviceToken)) if (string.IsNullOrWhiteSpace(deviceToken))
{ {
var inputError = DefaultResponse.InvalidInputError; var inputError = APIResponse.InvalidInputError;
inputError.status.message = "Deviece Toekn 오류"; // inputError.status.message = "Deviece Toekn 오류";
return StatusCode(500,inputError); return StatusCode(500,inputError);
} }
if (payload == null) if (payload == null)
{ {
var inputError = DefaultResponse.InvalidInputError; var inputError = APIResponse.InvalidInputError;
inputError.status.message = "payload 입력 오류"; // inputError.status.message = "payload 입력 오류";
return StatusCode(500,inputError); return StatusCode(500,inputError);
} }
@ -86,19 +86,11 @@ public class PushController : ControllerBase
var result = await pushService.SendPushNotificationAsync(deviceToken, payload); var result = await pushService.SendPushNotificationAsync(deviceToken, payload);
if (result.Success) if (result.Success)
{ {
return Ok(DefaultResponse.Success.JsonToString()); return Ok(APIResponse.Success());
} }
else else
{ {
return BadRequest(APIResponse.InternalSeverError());
var apnsError = DefaultResponse.InternalSeverError;
apnsError.status.message = $"{result.Message}";
return result.Code switch
{
"002" => StatusCode(002, apnsError),
"003" => StatusCode(003, apnsError),
"999" => StatusCode(999, apnsError)
};
} }
} }

View File

@ -40,7 +40,7 @@ public class UserController : ControllerBase
[CustomOperation("회원 정보 조회", "회원 정보 조회", "사용자")] [CustomOperation("회원 정보 조회", "회원 정보 조회", "사용자")]
public IActionResult GetUserData(string uid) public IActionResult GetUserData(string uid)
{ {
if (string.IsNullOrEmpty(uid)) return BadRequest(DefaultResponse.InvalidInputError); if (string.IsNullOrEmpty(uid)) return BadRequest(APIResponse.InvalidInputError);
try try
{ {
@ -71,7 +71,7 @@ public class UserController : ControllerBase
} }
catch (Exception ex) catch (Exception ex)
{ {
return StatusCode(500, DefaultResponse.UnknownError); return StatusCode(500, APIResponse.UnknownError);
} }
} }
@ -81,7 +81,7 @@ public class UserController : ControllerBase
{ {
// API 동작 파라미터 입력 값 확인 // API 동작 파라미터 입력 값 확인
if (string.IsNullOrEmpty(acctype) && string.IsNullOrEmpty(sns_id)) if (string.IsNullOrEmpty(acctype) && string.IsNullOrEmpty(sns_id))
return BadRequest(DefaultResponse.InvalidInputError); return BadRequest(APIResponse.InvalidInputError);
try try
{ {
@ -129,25 +129,12 @@ public class UserController : ControllerBase
// case 1: Login 테이블에 값이 없다 == 로그인이 처음 // case 1: Login 테이블에 값이 없다 == 로그인이 처음
// case 2: User 테이블에 값이 없다 == 이건 문제가 있는 상황 -> 해결은 회원가입 재 진행 시도 // case 2: User 테이블에 값이 없다 == 이건 문제가 있는 상황 -> 해결은 회원가입 재 진행 시도
// Login에는 있는데 User 테이블에 없다? 말이 안되긴 하는데... // Login에는 있는데 User 테이블에 없다? 말이 안되긴 하는데...
return Ok(new APIResponseStatus<dynamic> return Ok(APIResponse.Send("010", "로그인 정보가 없으므로 회원가입 진행",Empty));
{
status = new Status
{
code = "010",
message = "로그인 정보 없음 > 회원 가입 진행"
},
data = new
{
token = "",
refresh = ""
// bidList = new string[] { }
}
}.JsonToString());
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogInformation($"[로그인] 에러 발생 : {ex}"); _logger.LogInformation($"[로그인][에러] : {ex}");
return StatusCode(500, DefaultResponse.UnknownError); return StatusCode(500, APIResponse.UnknownError);
} }
} }
@ -159,7 +146,7 @@ public class UserController : ControllerBase
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(refresh)) if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(refresh))
{ {
var error = DefaultResponse.InvalidInputError; var error = APIResponse.InvalidInputError;
return Ok(error); return Ok(error);
} }
@ -183,28 +170,22 @@ public class UserController : ControllerBase
}) })
.ToListAsync(); .ToListAsync();
var response = new APIResponseStatus<List<AcademyName>> return Ok(APIResponse.Send("000","정상.",academies));
{
status = new Status
{
code = "000",
message = "정상"
},
data = academies
};
return Ok(response);
} }
catch (SecurityTokenException tokenEx) catch (TokenException tokenEx)
{ {
_logger.LogInformation($"[로그인][오류] 토큰 검증 : {tokenEx}"); _logger.LogInformation($"[로그인] : {tokenEx}");
return StatusCode(500, DefaultResponse.InvalidInputError); return StatusCode(500, APIResponse.InvalidInputError);
}
catch (RefreshRevokeException refreshEx)
{
_logger.LogInformation($"[로그인] : {refreshEx}");
return StatusCode(500, APIResponse.InvalidInputError);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogInformation($"[로그인][오류] 에러 발생 : {ex}"); _logger.LogInformation($"[로그인][에러] : {ex}");
return StatusCode(500, DefaultResponse.UnknownError); return StatusCode(500, APIResponse.UnknownError);
} }
} }
@ -213,11 +194,11 @@ public class UserController : ControllerBase
[CustomOperation("회원 가입", "사용자 회원 가입", "사용자")] [CustomOperation("회원 가입", "사용자 회원 가입", "사용자")]
public async Task<IActionResult> UserRegister([FromBody] UserAll request) public async Task<IActionResult> UserRegister([FromBody] UserAll request)
{ {
if (!ModelState.IsValid) return BadRequest(DefaultResponse.InvalidInputError); if (!ModelState.IsValid) return BadRequest(APIResponse.InvalidInputError);
var atIndext = request.email.IndexOf('@'); var atIndext = request.email.IndexOf('@');
var localPart_email = request.email.Substring(0, atIndext); var localPartEmail = request.email.Substring(0, atIndext);
var uid = $"AM{localPart_email}{DateTime.Now:yyyyMMdd}"; var uid = $"AM{localPartEmail}{DateTime.Now:yyyyMMdd}";
var user = new User var user = new User
{ {
@ -292,7 +273,8 @@ public class UserController : ControllerBase
{ {
// 로그아웃 하면 리프래시 토큰 만료 하는걸 넣어야 함 // 로그아웃 하면 리프래시 토큰 만료 하는걸 넣어야 함
/* */ /* */
// var value = await ValidateToken(token, refresh); var value = await _repositoryService.ValidateToken(token, refresh);
// _logger.LogInformation(value.uid); // _logger.LogInformation(value.uid);
// _logger.LogInformation(value.refresh); // _logger.LogInformation(value.refresh);
// _logger.LogInformation(value.token); // _logger.LogInformation(value.token);

View File

@ -0,0 +1,24 @@
using Microsoft.IdentityModel.Tokens;
using System;
namespace AcaMate.V1.Models;
/// <summary>
/// 입력 받은 토큰들(Access & Refresh) 자체에 문제가 있는 경우
/// </summary>
public class TokenException: Exception
{
public TokenException(string message) : base(message)
{
}
}
/// <summary>
/// 리프레시 토큰이 만료가 나있는 경우
/// </summary>
public class RefreshRevokeException: Exception
{
public RefreshRevokeException(string message) : base(message)
{
}
}

View File

@ -7,7 +7,9 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Security.Claims; using System.Security.Claims;
using AcaMate.V1.Models;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Microsoft.VisualBasic;
namespace AcaMate.V1.Services; namespace AcaMate.V1.Services;
@ -102,15 +104,18 @@ public class RepositoryService: IRepositoryService
var refreshToken = await _dbContext.RefreshTokens var refreshToken = await _dbContext.RefreshTokens
.FirstOrDefaultAsync(t => t.refresh_token == refresh); .FirstOrDefaultAsync(t => t.refresh_token == refresh);
if (refreshToken == null) if (refreshToken == null)
{ throw new TokenException("입력 받은 토큰 자체의 문제");
throw new SecurityTokenException("리프레시 토큰도 잘못되었음");
}
var uid = refreshToken.uid; var uid = refreshToken.uid;
if (refreshToken.revoke_Date < DateTime.Now)
throw new RefreshRevokeException("리프레시 토큰 해지");
if (refreshToken.expire_date > DateTime.Now) if (refreshToken.expire_date > DateTime.Now)
{ {
_logger.LogInformation($"리프레시 : {uid}"); _logger.LogInformation($"인증 완료 리프레시 : {uid}");
var access = _jwtTokenService.GenerateJwtToken(uid); var access = _jwtTokenService.GenerateJwtToken(uid);
return new ValidateToken return new ValidateToken
{ {
token = access, token = access,