[Spring] @RestControllerAdvice / @ExceptionHandler 다시 보기

snowballnote·2026년 10월 2일

Biz Assist에서 알림 수신자 API의 오류를 처리하면서
@RestControllerAdvice와 @ExceptionHandler를 사용했다.

@RestControllerAdvice(
        assignableTypes = NotificationSubscriberController.class
)
public class NotificationSubscriberApiExceptionHandler {
}

@RestControllerAdvice

여러 Controller에서 발생하는 예외를
한곳에서 처리할 수 있게 해준다.

이번에는

assignableTypes = NotificationSubscriberController.class

로 범위를 정해서
알림 수신자 API에서 발생한 예외만 처리하도록 했다.

@ExceptionHandler

특정 예외가 발생했을 때
어떤 응답을 보낼지 정한다.

@ExceptionHandler(
        DuplicateNotificationSubscriberException.class
)
public ResponseEntity<NotificationSubscriberErrorResponse> handleDuplicate(
        DuplicateNotificationSubscriberException exception
) {
    return response(
            HttpStatus.CONFLICT,
            exception.getMessage()
    );
}

중복 수신자가 등록되면

DuplicateNotificationSubscriberException
↓
409 CONFLICT

로 변환된다.

Biz Assist에서는 왜 썼나

수신자 등록 과정에서는 여러 오류가 생길 수 있었다.

잘못된 입력
→ 400 BAD_REQUEST

이미 등록된 수신자
→ 409 CONFLICT

없는 수신자
→ 404 NOT_FOUND

이걸 Controller마다 try-catch로 처리하지 않고
예외 처리 클래스로 따로 뺐다.

Controller는 더 단순해졌다

Controller에서는 그냥 Service를 호출한다.

@PostMapping
public ResponseEntity<NotificationSubscriberResponse> register(
        @RequestBody CreateNotificationSubscriberRequest request
) {
    return ResponseEntity
            .status(HttpStatus.CREATED)
            .body(
                    NotificationSubscriberResponse.from(
                            service.register(
                                    request.getEmail(),
                                    request.getName(),
                                    request.getNotificationType()
                            )
                    )
            );
}

오류가 발생하면
@RestControllerAdvice가 따로 처리한다.

다시 정리

@RestControllerAdvice
→ Controller 예외 처리를 한곳에 모음

@ExceptionHandler
→ 특정 예외를 어떤 응답으로 바꿀지 정의

Biz Assist에서는

알림 수신자 API의 입력 오류와 중복 오류를 HTTP 상태 코드로 변환하기 위해 사용했다.

Controller는 정상 흐름에 집중하고
예외 처리는 따로 분리한다고 생각하면 이해하기 쉽다.

profile
개발자로 이 험난한 세상 살아가기

0개의 댓글