2016-10-11 19 views
6

我有一個Spring Boot網絡應用程序,我明白我的自定義異常的ControllerAdvice類。問題是,如果沒有處理程序被發現Spring Boot不會拋出默認異常(發送json回客戶端)。沒有處理髮現的異常和靜態的recources春季啓動

我想是趕上NoHandlerFoundExceptionControllerAdvice類。要做到這一點我明確地配置

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

這招做這項工作,我能趕上NoHandlerFoundException,但現在它禁用Spring自動配置路徑靜態資源。所以我現在所有的靜態資源都不可用於客戶端。我試圖解決這個使用一個以上的配置不利於

spring.resources.static-locations=classpath:/resources/static/ 

有誰請指教如何在自動配置與spring.resources.add-mappings=false禁用靜態資源Spring Boot地圖?

謝謝!

+1

您是否找到任何解決方案? –

回答

1

而不是增加以下線配置屬性

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

編寫自定義錯誤的屬性如下:

@Configuration 
public class CustomErrorAttributes extends DefaultErrorAttributes { 

    @Bean 
    public ErrorAttributes errorAttributes() { 

     return new DefaultErrorAttributes() { 
      @Override 
      public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) { 

       Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace); 
       Map<String, Object> newErrorAttributes = new LinkedHashMap<String, Object>(); 
       Object errorMessage = requestAttributes.getAttribute(RequestDispatcher.ERROR_MESSAGE, RequestAttributes.SCOPE_REQUEST); 
       if (errorMessage != null) { 
        newErrorAttributes.put("response-type", "error"); 
        newErrorAttributes.put("error-code", errorAttributes.get("status")); 
        newErrorAttributes.put("message", errorAttributes.get("message")); 
        newErrorAttributes.put("error-message", errorAttributes.get("error")); 
       } 
       return newErrorAttributes; 
      } 

     }; 
    } 
} 
1

如果你的靜態資源僅限於特定的目錄,你可以只配置那些路徑由Spring靜態資源處理器處理:

spring.mvc.static-path-pattern=/doc/** 
spring.resources.static-locations=classpath:/static/doc/ 

您需要刪除此配置:

spring.resources.add-mappings=false