Spring Boot Rest – 如何配置404 – 找不到资源
我有一个工作弹簧靴rest服务。 当路径错误时,它不会返回任何内容。 根本没有回应。 同时它也不会抛出错误。 理想情况下,我预计会发现404错误。
我有一个GlobalErrorHandler
@ControllerAdvice public class GlobalErrorHandler extends ResponseEntityExceptionHandler { }
ResponseEntityExceptionHandler中有此方法
protected ResponseEntity handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); }
我在我的属性中标记了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 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
– 需要定义适用于所有@RequestMappings
@ExceptionHandler
。
@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
覆盖响应的@ExceptionHandler
。 NoHandlerFoundException
是一个exception,它将在Spring无法委托请求时生成(404情况)。 您还可以指定Throwable
来覆盖任何exception。
其次,你需要告诉Spring在404的情况下抛出exception(无法解析处理程序):
@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" }