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

新手上路,请多包涵

我得到了一个有效的 spring boot rest 服务。当路径错误时,它不会返回任何东西。完全没有反应。同时它也不会抛出错误。理想情况下,我预计会出现 404 not found 错误。

我有一个 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 not found 响应返回给客户

我提到了很多话题,但没有人遇到过这种麻烦。

这是我的主要应用程序类

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

原文由 juniorbansal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 571
1 个回答

解决方案非常简单:

首先,您需要实现将处理所有错误情况的控制器。此控制器必须有 @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");
    }
}

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

使用未定义的 URL 时的结果

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

更新:如果您使用 application.properties 配置 SpringBoot 应用程序,那么您需要添加以下属性,而不是在 main 方法中配置 DispatcherServlet (感谢@mengchengfeng):

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

原文由 Ilya Ovesnov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题