Spring Boot Rest - 如何配置404 - 找不到资源 [英] Spring Boot Rest - How to configure 404 - resource not found

查看:705
本文介绍了Spring Boot Rest - 如何配置404 - 找不到资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有效的弹簧靴休息服务。当路径错误时,它不会返回任何内容。根本没有回应。同时它也不会抛出错误。理想情况下,我预计会发现404未找到错误。

I got a working spring boot rest service. When the path is wrong it doesn't return anything. No response At all. At the same time it doesn't throw error either. Ideally I expected a 404 not found error.

我有一个GlobalErrorHandler

I got a GlobalErrorHandler

@ControllerAdvice
public class GlobalErrorHandler extends ResponseEntityExceptionHandler {

}

ResponseEntityExceptionHandler中有这个方法

There is this method in 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未找到的回复扔回客户

What else must I do for this service to throw a 404 not found response back to clients

我提到了很多线程,并没有看到任何人遇到这个问题。

I referred a lot of threads and don't see this trouble faced by anybody.

这是我的主应用程序类

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


推荐答案

解决方案非常简单:

首先您需要实现能够处理所有错误情况的控制器。此控制器必须具有 @ControllerAdvice - 需要定义适用于所有 @ExceptionHandler RequestMappings

First you need to implement the controller that will handle all error cases. This controller must have @ControllerAdvice -- required to define @ExceptionHandler that apply to all @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");
    }
}

提供想要覆盖<$ c中的响应的异常$ C> @ExceptionHandler 。 NoHandlerFoundException 是一个异常,当Spring无法委托请求时(404情况)将生成该异常。你也可以指定 Throwable 来覆盖任何例外。

Provide exception you want to override response in @ExceptionHandler. NoHandlerFoundException is an exception that will be generated when Spring will not be able to delegate request (404 case). You also can specify Throwable to override any exceptions.

第二次你需要告诉Spring在404的情况下抛出异常(无法解析处理程序):

Second you need to tell Spring to throw exception in case of 404 (could not resolve handler):

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

使用未定义的网址时的结果

Result when I use non defined URL

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

这篇关于Spring Boot Rest - 如何配置404 - 找不到资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆