1. IDE
Intellij
2. 오늘 공부 내용
API 공통 응답
- 모든 API 응답을 일정한 형식으로 반환하여 클라이언트가 예측 가능한 방식으로 결과를 처리할 수 있도록 하는 구조
- 성공 및 실패 응답의 구조를 통일할 수 있음
구현 방법
- 응답 객체 만들기
public class ApiResponse<T> {
private String status;
private String message;
private T data;
public ApiResponse(String status, String message, T data) {
this.status = status;
this.message = message;
this.data = data;
}
// getters and setters
}
- 컨트롤러에서 공통 응답 변환
@RestController
@RequestMapping("/api/v1")
public class UserController {
@GetMapping("/users/{id}")
public ResponseEntity<ApiResponse<User>> getUser(@PathVariable Long id) {
User user = userService.getUserById(id);
return ResponseEntity.ok(new ApiResponse<>("SUCCESS", "User found", user));
}
}
장단점
- 장점
- 일관성 있는 응답 구조
- 코드 중복 감소
- 클라이언트와의 통신 간소화
- 표준화된 오류 처리
- 확장성
- 단점
- 추가적인 오버헤드
- 복잡성 증가
- 유연성 감소
- 에러 상태 코드 사용 제한
- 대용량 데이터 처리 시 비효율성
글로벌 예외 처리
- 애플리케이션 내에서 발생하는 모든 에외를 하나의 곳에서 처리하여 일관된 에러 응답을 제공하는 방식
- 코드 중복을 줄이고, 다양한 예외에 대해 사용자에게 통일된 오류 메시지를 전달할 수 있음
구현 방법
- ExceptionHandler를 포함하는 클래스를 생성
@ControllerAdvice
public class GlobalExceptionHandler {
// 특정 예외 처리 (예: IllegalArgumentException)
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<ApiResponse<Void>> handleIllegalArgumentException(IllegalArgumentException ex) {
ApiResponse<Void> response = new ApiResponse<>("FAILURE", ex.getMessage(), null);
return ResponseEntity.badRequest().body(response);
}
// 일반적인 예외 처리
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Void>> handleGeneralException(Exception ex) {
ApiResponse<Void> response = new ApiResponse<>("FAILURE", "An unexpected error occurred", null);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}
- 예외 처리 과정 설명
@ControllerAdvice: 모든 컨트롤러에서 발생하는 예외를 처리하는 클래스임을 명시합니다.
@ExceptionHandler: 처리할 특정 예외를 지정합니다. 위 예제에서는 IllegalArgumentException과 Exception을 처리하고 있습니다.
- 예외 발생 시, API 공통 응답 구조를 사용해 사용자에게 일관된 에러 메시지를 전달합니다.
장단점