스프링 관련/스프링 프레임워크
@RestControllerAdvice, @ExceptionHandler(RuntimeException.class) 이용한 예외처리 분리
문자메일
2022. 11. 20. 18:14
@RestControllerAdvice : 스프링 빈에 등록된 @Controller, @RestController 클래스 전체 대상으로 @ExceptionHandler를 적용할 수 있는 설정
@ExceptionHandler : @Controller, @RestController 클래스 안에서 예외가 발생한 것을 적용된 Bean 내에서 처리할 수 있게 하는 기능을 제공한다.
@Slf4j
@RestControllerAdvice
public class GlobalControllerAdvice {
@ExceptionHandler(SnsApplicationException.class)
public ResponseEntity<?> applicationHandler(SnsApplicationException e){
log.error("Error occurs {}", e.toString());
return ResponseEntity.status(e.getErrorCode().getStatus())
.body(Response.error(e.getErrorCode().name()));
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<?> applicationHandler(RuntimeException e){
log.error("Error occurs {}", e.toString());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Response.error(ErrorCode.INTERNAL_SERVER_ERROR.name()));
}
}