👣 개요
예외 처리를 위해 try - catch - finally 문을 사용할 수도 있지만
해당 방법은 가독성을 해치기도 하고 반복된 코드를 계속해서 작성해야 하는 불상사가 발생하곤 한다.
때문에 이러한 과정을 @Transactional과 같이 AOP로 처리를 할 수 있는 방법에 대해 작성하고자 한다.
try-catch 문으로 인해 가독성 떨어지게 작성된 코드 예시
public class UserService {
public void updateUser(User user) {
try {
// 사용자 정보 업데이트 로직
userRepository.update(user);
} catch (DataAccessException ex) {
// 데이터베이스 업데이트에 실패한 경우
log.error("Failed to update user: " + ex.getMessage());
throw new ServiceException("Failed to update user.", ex);
} catch (InvalidDataException ex) {
// 유효하지 않은 데이터로 업데이트를 시도한 경우
log.error("Invalid data for user update: " + ex.getMessage());
throw new ServiceException("Invalid data for user update.", ex);
} catch (Exception ex) {
// 기타 예외 처리
log.error("An unexpected error occurred: " + ex.getMessage());
throw new ServiceException("An unexpected error occurred.", ex);
}
}
// 다른 메서드들...
}
👣 특정 Controller에서의 예외 처리 - @ExceptionHandler
@ExceptionHandler같은 경우는 @Controller가 적용된 Controller 내에서 발생하는
예외를 잡아서 하나의 메서드에서 처리해주는 기능을 한다.
@RestController
public class MyRestController {
...
@ExceptionHandler(NullPointerException.class)
public ErrorResponse npeHandler(NullPointerException e) {
...
}
}
- Controller, RestController에만 적용가능하다. (@Service같은 빈에서는 안됨.)
- @ExceptionHandler를 등록한 Controller에만 적용된다.
다른 Controller에서는 정의한 위 예시에서 정의한 npeHandler 함수가 적용되지 않는다.
👣 모든 Controller에서의 예외 처리 - @ExceptionHandler & @ControllerAdvice
@ExceptionHandler와 @ControllerAdvice 함께 적용하면 전역적으로 예외 처리를 할 수 있다.
@RestControllerAdvice
public class Advice {
@ExceptionHandler(CustomException.class)
public String customHandler() {
...
}
}
'Spring Boot' 카테고리의 다른 글
@Transactional (0) | 2023.07.30 |
---|---|
Lombok (0) | 2023.07.29 |
SpEL - Spring Expression Language (0) | 2023.07.29 |
Spring Boot AOP (0) | 2023.07.29 |
Spring Boot Bean 등록 방법 5가지 (0) | 2023.07.29 |