@RestController
@RequiredArgsConstructor
public class ExceptionHandlerController {
private final ExceptionHandlerService exceptionHandlerService;
@RequestMapping("/v1/exception")
public void illegalArgumentException() {
throw new IllegalArgumentException("IllegalArgumentException 발생");
}
@RequestMapping("/v2/exception")
public void nullPointerException() {
throw new NullPointerException("NPE 발생");
}
@RequestMapping("/v3/exception")
public void serviceLayerException() {
exceptionHandlerService.throwNewIllegalArgumentException();
}
// IllegalArgumentException을 처리하는 메서드
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Map<String, String>> handleIllegalArgumentException(IllegalArgumentException ex) {
Map<String, String> response = new HashMap<>();
response.put("error", ex.getMessage());
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(response);
}
}
@RestController
public class NonExceptionHandlerController {
@RequestMapping("/v4/exception")
public void illegalArgumentException() {
throw new IllegalArgumentException("IllegalArgumentException 발생");
}
}
@Service
public class ExceptionHandlerService {
public void throwNewIllegalArgumentException() {
throw new IllegalArgumentException("ServiceLayer Exception");
}
}
문제점
Controller 코드에 Exception 처리를 위한 책임이 추가된다.(단일 책임 원칙 위반)
단일 컨트롤러 내의 예외만 처리가 가능하다.(컨트롤러 예외처리 중복코드)
코드 재사용, 유지보수성 부족
CustomException 사용자 정의 Exception을 만들어서 처리할 수 있다.
@ControllerAdvice
📌 @ControllerAdvice와 동일한 기능을 제공하지만 @RestController를 포함하고 있어 반환 값이 자동으로 JSON 형태로 변환되며 REST API에서 발생하는 예외를 처리할 때 사용한다.
Application 전역에서 발생한 예외를 처리한다.
@RestControllerAdvice
REST API의 예외를 처리한다.
반환 값이 JSON이다.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Map<String, String>> handleIllegalArgumentException(IllegalArgumentException ex) {
Map<String, String> response = new HashMap<>();
response.put("error", ex.getMessage());
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(response);
}
}