404 No Handler Found는 기본적으로 Dispatcher Servlet에서 처리한다. 즉 ControllerAdice에서 처리할 수 없다.
이를 가능하게 하기 위해서는 아래 내용을 application.yml에 추가해주어야 한다.
spring:
mvc:
throw-exception-if-no-handler-found: true
web:
resources:
add-mappings: false
throw-exception-if-no-handler-found
true로 설정시 dispatcher servlet에서 요청에 대한 핸들러를 찾을 때 요청을 처리할 수 없는 핸들러가 없다면 (mappedHandler가 null이라면) NoHandlerFoundException 예외를 발생시킨다.
add-mappings
false로 설정시 스프링에서 기본적으로 제공하는 정적 자원 요청 매핑을 사용하지 않는다.
위와 같이 추가한 이후에는 controlleradvice에서 NoHandlerFoundException을 처리할 수 있게 된다.
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<ErrorResponse> noHandlerFoundException(NoHandlerFoundException e) {
ErrorResponse errorResponse = ErrorResponse.builder()
.status(ErrorCode.NO_HANDLER_FOUND.getStatus())
.message(ErrorCode.NO_HANDLER_FOUND.getMessage())
.code(ErrorCode.NO_HANDLER_FOUND.getCode())
.detail("api does not exist")
.build();
return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
}