Exeption
을 공통으로 처리하는 방법은 크게 두 가지가 있다.
AbstractHandlerExceptionResolver
를 상속받아 ExceptionResolver
를 구현@ControllerAdvice
, @ExceptionHandler
어노테이션을 사용하여 ExceptionHandler를 구현
ExceptionResolver
구현 방법은 지난 포스팅에 정리했고, 이번엔ExceptionHandler
구현 방법에 대해 기록합니다. 🤓
AOP
(관점지향 프로그래밍)를 적용해 예외를 전역적으로 처리할 수 있다.@ExceptionHandler
, @InitBinder
, @ModelAttribute
가 적용된 메소드에 AOP를 적용하기 위해 고안되었다.@Component
가 포함되어 있기 때문에, 빈으로 관리된다.@RestControllerAdvice
어노테이션은 @ResponseBody
을 포함하기 때문에, 응답값을 JSON
형태로 내려준다.package com.money.moa.common.exception.handler
import com.money.moa.common.dto.ResponseDto
import com.money.moa.common.exception.CommonException
import org.springframework.core.Ordered
import org.springframework.core.annotation.Order
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
class CommonExceptionHandler {
@ExceptionHandler(CommonException::class)
fun handleBizException(ex: CommonException): ResponseEntity<ResponseDto<*>> {
val response = ResponseDto(
code = ex.code ?: HttpStatus.INTERNAL_SERVER_ERROR.value(),
message = ex.message,
error = ex.message,
response = null // 일단 null
)
return ResponseEntity.status(response.code).body(response)
}
}
출처
[Spring] 전역 예외 처리를 위한 @ControllerAdvice와 @RestControllerAdvice
@RestControllerAdvice를 이용한 예외처리