Spring boot handling 404 error / NoHandlerFoundException

북마크 추가

spring boot에서 404에러를 처리하는 방법입니다.

 404에러는 컨트롤러를 타기전에 발생해서 Throwable Exception으로 잡히지 않아 설정이 필요합니다.

1. @ControllerAdvice

 

@ControllerAdvice
public class TestControllerAdvice {

/**
* Throwable Exception
*/
@ExceptionHandler(Throwable.class)
public void handleServerError(HttpServletRequest req, Exception ex) {
//todo

}


/**
* 404 not found
*/
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public void NoHandlerFoundException(HttpServletRequest req, Exception ex) {
//todo

}
}

TestControllerAdvice.java 파일을 생성하여 404 핸들러를 추가해 줍니다.


2. @Configuration

 

@Configuration
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter {

@Bean
public DispatcherServlet dispatcherServlet() {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return dispatcherServlet;
}

}


WebAppConfig.java 파일을 생성 후 WebMvcConfigurerAdapter를 상속받고 dispatcherServlet 설정을 해줍니다.

* @EnableWebMvc 어노테이션과 WebMvcConfigurerAdapter 상속을 받지 않고 DispatcherServlet만 설정하면  동작하지 않습니다.

 

위 설정을 한 후 404에러가 나게되면 TestControllerAdvice의 NoHandlerFoundException을 타게 되고 

위 method에서 404 에러에 대한 후 처리를 하면 됩니다.

 

AD
관리자
2017-06-02 14:15
SHARE