Api 명세서를 보면서 개발을 진행하다가 공통 응답 클래스를 한 번 묶어서 프론트와의 협업 과정에서 더 편하게 개발 가능하도록 하였다.
공통 응답 클래스
1)정상 응답 예시
{
"code": 200,
"message": "SUCCESS",
"data": {
"id": 2,
"title": "공지사항 작성 테스트",
"body": "123123123",
"author": "채정흠민정흠이다",
"createdAt": "2024-01-23T10:19:54.270594",
"updatedAt": "2024-01-23T10:19:54.270594"
}
}
2) 예외 응답 예시
{
"code": 400,
"message": "FAILURE",
"data": null
}
@Getter
@NoArgsConstructor
public class Response<T> {
private int code;
private String message;
private T data;
@Builder
public Response(ResponseType responseType, T data) {
this.code = responseType.getCode();
this.message = responseType.getMessage();
this.data = data;
}
public static Response success() {
return Response.builder()
.responseType(SUCCESS)
.build();
}
public static <T> Response<T> success(T data) {
return new Response<>(SUCCESS, data);
}
public static Response failure() {
return Response.builder()
.responseType(FAILURE)
.build();
}
}
Response<T> 클래스는 code , message , data 세가지의 타입을 가진다.
생성한 Response 클래스는 controller 에서 다음과 같이 사용 가능하다
@GetMapping("/posts")
public ResponseEntity getNotices() {
List<NoticeResponseDto> notices = noticeService.getNotices();
if (!notices.isEmpty()) {
return new ResponseEntity<>(Response.success(notices), HttpStatus.OK);
} else {
return new ResponseEntity<>(Response.failure(), HttpStatus.BAD_REQUEST);
}
}
겪었던 어려움
JPA 를 사용하면서 findById 를 사용할땐 Optional 로 null 값일 경우 IllegalArgumentException 를 통해서 처리를 하다보니 failure 일 경우 ResponseEntity를 반환하기 전 Exception이 터져버려 공통 응답 형식이 적용이 안되는 현상이 발생하였고,
결국 컨트롤러에서 한번더 try catch 를 이용하여 처리하였다.
@PutMapping("/post/{id}")
public ResponseEntity updateNotice(@PathVariable Long id, @RequestBody NoticeRequestDto requestDto)
throws Exception {
try {
NoticeResponseDto noticeResponseDto = noticeService.updateNotice(id, requestDto);
return new ResponseEntity<>(Response.success(noticeResponseDto), HttpStatus.OK);
} catch (IllegalArgumentException ex) {
return new ResponseEntity<>(Response.failure(), HttpStatus.BAD_REQUEST);
}
}