2016-04-20 48 views
7

我得到了一个可用的spring boot rest服务。当路径错误时,它不会返回任何内容。没有反应。同时它也不会抛出错误。理想情况下,我预计404未找到错误。Spring Boot Rest - 如何配置404 - 资源未找到

我得到了GlobalErrorHandler

@ControllerAdvice 
public class GlobalErrorHandler extends ResponseEntityExceptionHandler { 

} 

有这种方法ResponseEntityExceptionHandler

protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, 
                HttpStatus status, WebRequest request) { 

    return handleExceptionInternal(ex, null, headers, status, request); 
} 

我也标志着我的财产error.whitelabel.enabled=false

我必须为这个服务抛出哪些其他404未找到回应客户的回应

我提到了很多线程,并没有看到任何人面临这种​​麻烦。

这是我的主应用程序类

@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; 
    } 
} 

回答

13

该解决方案是很容易的:你需要实现将处理所有的错误情况下,控制器

首先。该控制器必须具有@ControllerAdvice - 需要定义适用于所有@RequestMappings@ExceptionHandler

@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"); 
    } 
} 

提供例外要覆盖@ExceptionHandler中的响应。 NoHandlerFoundException是Spring将无法委托请求时生成的异常(404 case)。您也可以指定Throwable覆盖任何例外。

你要告诉Spring抛出异常在404的情况下(无法解析处理):

@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); 
    } 
} 

结果,当我使用非定义的URL

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

谢谢。即使做了这个改变,我仍然没有看到任何回应。请帮忙!!! – Shiv

+0

你能发布你的过滤器实现吗? CorrelationHeaderFilter将处理每个请求,可能是它不适合你的原因。我测试了一个非常接近你的代码,它工作,如果我评论过滤器,添加'@EnableWebMvc'和评论不需要注释像'@EnableSwagger','@@ EnableJpaRepositories','@@ EnableAspectJAutoProxy'。 –

+0

我可以发布简单的应用程序到github,如果你想 –