Spring Boot Rest - How to configure 404 - resource not found

I got a working spring boot rest service. When the path is wrong, it returns nothing. No answer. At the same time, this does not produce an error. Ideally, I expected 404 not found error.

I got GlobalErrorHandler

@ControllerAdvice public class GlobalErrorHandler extends ResponseEntityExceptionHandler { } 

There is this method in ResponseEntityExceptionHandler

 protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); } 

I noted error.whitelabel.enabled=false in my properties

What else should I do for this service to send 404 not found answer to clients

I have referred to many topics and do not see anyone who could run into this problem.

This is my main application class.

  @EnableAutoConfiguration // Sprint Boot Auto Configuration @ComponentScan(basePackages = "com.xxxx") @EnableJpaRepositories("com.xxxxxxxx") // To segregate MongoDB // and JPA repositories. // Otherwise not needed. @EnableSwagger // auto generation of API docs @SpringBootApplication @EnableAspectJAutoProxy @EnableConfigurationProperties public class Application extends SpringBootServletInitializer { private static Class<Application> appClass = Application.class; @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(appClass).properties(getProperties()); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public FilterRegistrationBean correlationHeaderFilter() { FilterRegistrationBean filterRegBean = new FilterRegistrationBean(); filterRegBean.setFilter(new CorrelationHeaderFilter()); filterRegBean.setUrlPatterns(Arrays.asList("/*")); return filterRegBean; } @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource dataSource() { return DataSourceBuilder.create().build(); } static Properties getProperties() { Properties props = new Properties(); props.put("spring.config.location", "classpath:/"); return props; } @Bean public WebMvcConfigurerAdapter webMvcConfigurerAdapter() { WebMvcConfigurerAdapter webMvcConfigurerAdapter = new WebMvcConfigurerAdapter() { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false).favorParameter(true).parameterName("media-type") .ignoreAcceptHeader(false).useJaf(false).defaultContentType(MediaType.APPLICATION_JSON) .mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON); } }; return webMvcConfigurerAdapter; } @Bean public RequestMappingHandlerMapping defaultAnnotationHandlerMapping() { RequestMappingHandlerMapping bean = new RequestMappingHandlerMapping(); bean.setUseSuffixPatternMatch(false); return bean; } } 
+9
java spring rest spring-boot spring-mvc
source share
2 answers

The solution is quite simple:

First you need to implement a controller that will handle all cases of errors. This controller must have @ControllerAdvice - required to define @ExceptionHandler which applies to all @RequestMappings .

 @ControllerAdvice public class ExceptionHandlerController { @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(value= HttpStatus.NOT_FOUND) @ResponseBody public ErrorResponse requestHandlingNoHandlerFound() { return new ErrorResponse("custom_404", "message for 404 error code"); } } 

Provide the exception you want to override the response in @ExceptionHandler . NoHandlerFoundException is an exception that will be thrown when Spring cannot delegate the request (case 404). You can also specify Throwable to override any exceptions.

Secondly, you have to tell Spring to throw an exception in case 404 (the handler could not be resolved):

 @SpringBootApplication @EnableWebMvc public class Application { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(Application.class, args); DispatcherServlet dispatcherServlet = (DispatcherServlet)ctx.getBean("dispatcherServlet"); dispatcherServlet.setThrowExceptionIfNoHandlerFound(true); } } 

Result when I use an undefined URL

 { "errorCode": "custom_404", "errorMessage": "message for 404 error code" } 

UPDATE : If you are configuring a SpringBoot application.properties using application.properties you need to add the following properties instead of setting the DispatcherServlet in the main method (thanks @mengchengfeng):

 spring.mvc.throw-exception-if-no-handler-found=true spring.resources.add-mappings=false 
+17
source share

when I use the above solution, I get an exception. Can anyone help?

java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped to [class org.springframework.web.servlet.NoHandlerFoundException]:

0
source share

All Articles