2016-04-20 44 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,如果你想 –