공통 응답 객체
- 모든 API에 대한 응답 공통 DTO 생성
- 모든 응답에 일관된 형식
공통 응답 객체 생성
@Getter
public class CommonResponse<T> {
private final int code;
private final HttpStatus status;
private final T content;
public CommonResponse(HttpStatus status, T content) {
this.code = status.value();
this.status = status;
this.content = content;
}
}
예시
public ResponseEntity<CommonResponse<?>> create() {...}
public ResponseEntity<CommonResponse<List<GetUserResponse>>> getAll() {...}
public ResponseEntity<CommonResponse<UpdateUserResponse>> update() {...}
<?> 사용하지말고 명확하게 작성하여 해당 코드만 보고 어떤 내용인지 알 수 있도록 함
공통 예외 처리
- 예외 정보를 한 곳에서 관리
a. 유지보수 편해짐
- 예외를 던질 때 오타/중복/일관성 문제가 없어짐
ExceptionEnum 생성
@Getter
public enum ExceptionCode {
NOT_FOUND_SCHEDULE(HttpStatus.BAD_REQUEST, "찾으시는 일정이없습니다"),
NOT_FOUND_USER(HttpStatus.BAD_REQUEST, "없는 유저입니다"),
EXIST_EMAIL(HttpStatus.BAD_REQUEST, "존재하는 이메일입니다"),
UN_AUTHORIZED(HttpStatus.UNAUTHORIZED, "이메일과 비밀번호가 일치하지 않습니다"),
FORBIDDEN(HttpStatus.FORBIDDEN, "잘못된 접근입니다"),
NOT_FOUND_COMMENT(HttpStatus.BAD_REQUEST, "댓글이 존재하지 않습니다");
private final HttpStatus status;
private final String message;
ExceptionCode(HttpStatus status, String message) {
this.status = status;
this.message = message;
}
}
CustomException 생성
@Getter
public class CustomException extends RuntimeException {
private final ExceptionCode exceptionCode;
public CustomException(String message, ExceptionCode exceptionCode) {
super(exceptionCode.getMessage());
this.exceptionCode = exceptionCode;
}
}
- 각 도메인별 하위 Exception 생성 -> 예외 구분이 쉬워짐, 유지보수 수월
예시
@Getter
public class UserCustomException extends CustomException {
public UserCustomException(ExceptionCode exceptionCode) {
super(exceptionCode);
}
}
정리
CommonResponse<T> 장점
1. 모든 API 응답 형태를 일관성 있게 유지
{
"code": 200,
"status": "OK",
"content": { ... }
}
2. 성공 / 실패 응답을 같은 포맷으로 만듦
# 성공
{
"code": 200,
"status": "OK",
"content": {
"scheduleId": 1,
"title": "일정 제목"
}
}
# 실패
{
"code": 400,
"status": "BAD_REQUEST",
"content": "없는 유저입니다"
}
Generic 타입으로 어떤 타입이든 가능
CommonResponse<CreateUserResponse>
CommonResponse<List<GetCommentResponse>>
CommonResponse<Void>
에러 처리와 연동
@ExceptionHandler(CustomException.class)
public ResponseEntity<CommonResponse<?>> serviceException(CustomException e) {
CommonResponse<String> response = new CommonResponse<>(e.getExceptionCode().getStatus(), e.getMessage());
return ResponseEntity.status(response.getStatus()).body(response);
}