没有处理程序在spring boot中发现异常和静态资源

Vad*_*dOs 7 java spring-boot

我有一个Spring BootWeb应用程序,我在ControllerAdvice课堂上捕获自定义异常.问题是Spring Boot如果没有找到处理程序(它发送json回客户端),默认情况下不会抛出异常.

我要的是赶NoHandlerFoundException在我的ControllerAdvice课.为了实现这一点,我明确配置了

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
Run Code Online (Sandbox Code Playgroud)

这个技巧完成了这项工作,我NoHandlerFoundException现在可以抓住,但它禁止Spring自动配置静态资源的路径.所以我的所有静态资源现在都不能用于客户端.我试图使用一个没有帮助的配置来解决这个问题

spring.resources.static-locations=classpath:/resources/static/
Run Code Online (Sandbox Code Playgroud)

有人可以建议如何在Spring Boot禁用自动配置时映射静态资源spring.resources.add-mappings=false吗?

谢谢!

Jam*_*mes 5

如果您的静态资源仅限于特定的URL路径,则只能配置Spring静态资源处理程序要处理的那些路径。在此示例中,/docURL路径由/resources/static/doc/classpath文件夹中的静态资源提供:

spring.mvc.static-path-pattern=/doc/**
spring.resources.static-locations=classpath:/resources/static/doc/
Run Code Online (Sandbox Code Playgroud)

您需要删除此配置:

spring.resources.add-mappings=false
Run Code Online (Sandbox Code Playgroud)


小智 1

而不是将以下行添加到配置属性

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
Run Code Online (Sandbox Code Playgroud)

编写您的自定义错误属性,如下所示:

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

        };
    }
} 
Run Code Online (Sandbox Code Playgroud)