IT'S DO
article thumbnail
728x90

Rest api에서는 사용자가 알아볼 수 있게 http 상태코드를 제공하는 것이 좋다고 했다. 그래서 해당 부분을

맞춰서 개발하는 도중에, 사용자에게 404에러 일시, message 문구를 변경해보려고 했다.
그렇지만, 없는 페이지 경로를 던져도, error : Not found, message : No message available은 고쳐지지 않았다.
하지만, 서치로 바꾸는 법을 알게되어서 정리하게 되었다.

 

# 증상 : 

 

여기에서 나오는 error 및 message를  바꿔 볼려고 했다.

 

# 해결법 : 

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {


    @Override
    public ResponseEntity<Object> handleNoHandlerFoundException(
            NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        Map<String, Object> body = new HashMap<>();
        body.put("timestamp", new Date());
        body.put("status", status.value());
        body.put("error", "Not Found");
        body.put("message", "The requested API does not exist");
        return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
    }

}

커스텀익셉션핸들러를 만들어서 아래와 같이 NoHnadlerFoundException의 @Override를 하면 된다고 한다.

 

그래서 넣고 다시 api를 호출 해보았다.

오잉?

그대로 였다.

 

문법이 이상한가 싶어서, 계속 찾게 되었지만, 그 어떤 것을 해도 다른 에러는 모를까, 위와 같은 출력화면이 계속 되었다.

 

그러는 도중에, 찾게 되었다. 결론 부터 말하자면 설정 문제였다.

 

# 추가 해준 것

application.yml 

spring:
  mvc:
    throw-exception-if-no-handler-found: true
    dispatch-options-request: false
  web:
    resources:
      add-mappings: false

mvc 안에 throw-exception, dispatch-option 그리고 web에 resources: add-mappings 둘다 넣어줘야한다. mvc와 web 둘중에 하나라도 없으면 안된다.

 

그 후에 다시 api 호출해봤다.

 

 

profile

IT'S DO

@멋진놈

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!