Spring Boot Rest - 如何配置404 - 找不到资源

jun*_*sal 11 java rest spring spring-mvc spring-boot

我得到了一个有效的弹簧靴休息服务.当路径错误时,它不会返回任何内容.完全没有回应.同时它也不会抛出错误.理想情况下,我期望404找不到错误.

我有一个GlobalErrorHandler

@ControllerAdvice
public class GlobalErrorHandler extends ResponseEntityExceptionHandler {

}
Run Code Online (Sandbox Code Playgroud)

ResponseEntityExceptionHandler中有此方法

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

    return handleExceptionInternal(ex, null, headers, status, request);
}
Run Code Online (Sandbox Code Playgroud)

我已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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ily*_*nov 21

解决方案非常简单:

首先,您需要实现将处理所有错误情况的控制器.该控制器必须具有@ControllerAdvice- 必须定义@ExceptionHandler适用于所有人@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

提供要覆盖响应的异常@ExceptionHandler.NoHandlerFoundException是Spring将无法委托请求时生成的异常(404情况).您还可以指定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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用未定义的URL时的结果

{
    "errorCode": "custom_404",
    "errorMessage": "message for 404 error code"
}
Run Code Online (Sandbox Code Playgroud)

  • 如果有其他人遇到代码示例的问题,当我使用属性而不是main内部配置调度程序servlet时,自定义ControllerAdvice适用于我的**Spring Boot**应用程序:`spring.mvc.throw-exception-if -no-handler-found = true spring.resources.add-mappings = false`在我删除了main中的dispatcherServlet配置并使用application.properties中的上述两个属性后,错误被正确路由到我的ControllerAdvice.希望这有助于某人! (15认同)
  • 这确实有帮助,但取代了 spring.resources.add-mappings=false ,它在 Spring boot 2+ 中已被 spring.web.resources.add-mappings=false 弃用。谢谢。 (2认同)