2026.02.10 - TIL 에서 시작
1. RestControllerAdvice란?
- RestControllerAdvice는 ControllerAdvice와 ResponseBody를 합친 어노테이션
- ControllerAdvice의 역할을 수행하며, ResponseBody을 통해 객체를 반환할 수 있다.
즉, Spring에서 여러 Controller에 걸쳐 발생하는 예외를 한 곳에서 전역적으로 처리하기 위해 사용.
(RestControllerAdvice지만, Controller 어노테이션에도 적용됨) (Rest가 붙은 이유는 ResponseBody을 통해 Json / XML 형태로 반환되기 때문이지, 모든 Controller에 적용됨)
2. ControllerAdvice란?
- ExceptionHandler (현대에는 이것을 주로 사용, But 아래 어노테이션도 가능)
- ModelAttribute
- InitBinder
가 적용된 메소드에 AOP을 적용. 에러가 발생헀을 때 해당 에러를 핸들링하는 ExceptionHandler의 메소드를 실행합니다.
3. Example
@RestControllerAdvice
// @RestControllerAdvice(basePackages = ["com.example.api"]) 로 특정 패키지에 제한할 수 있음
class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException::class)
fun handleBadRequest(e: IllegalArgumentException): ResponseEntity<ErrorResponse> {
val errorResponse = ErrorResponse(
status = HttpStatus.BAD_REQUEST.value(),
message = e.message ?: "Invalid request"
)
return ResponseEntity(errorResponse, HttpStatus.BAD_REQUEST)
}
@ExceptionHandler(Exception::class)
fun handleInternalError(e: Exception): ResponseEntity<ErrorResponse> {
val errorResponse = ErrorResponse(
status = HttpStatus.INTERNAL_SERVER_ERROR.value(),
message = "Internal server error occurred"
)
return ResponseEntity(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
data class ErrorResponse(val status: Int, val message: String)
도움이 된 글: