我正在开发一个使用 spring-boot (v2 M3) 和 spring-webflux 的项目。 在编写功能时,我发现我的微服务返回了 Http 200 状态代码,同时返回了 Flux 中的错误。
所以,我做了一个简单的测试: 我创建了一个简单的 Controller
@RestController
@RequestMapping(value = "/test")
public class TestController {
@GetMapping(value = "/errors")
public Flux<Object> getErrors() {
return Flux.error(new RuntimeException("test"));
}
}
使用简单的异常处理程序:
@ControllerAdvice
public class TestExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(TestExceptionHandler.class);
@ExceptionHandler(value = { RuntimeException.class })
public ResponseEntity<String> handleServerError(final RuntimeException e) {
LOGGER.error(e.getMessage(), e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
我在集成测试中使用 webTestClient 测试结果:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource("classpath:test.properties")
public class TestErrorsIT {
@Autowired
private WebTestClient webTestClient;
@Test
public void getErrors() {
this.webTestClient.get().uri("/test/errors").accept(MediaType.APPLICATION_STREAM_JSON).exchange().expectStatus()
.is5xxServerError();
}
}
结果,我的测试失败了,因为返回错误通量的 Controller 返回 200 状态代码而不是 503 状态代码(异常日志“test”在我的控制台中得到了很好的跟踪)。你知道为什么吗?
java.lang.AssertionError: Range for response status value 200 expected: but was:
GET http://localhost:54432/test/errors WebTestClient-Request-Id: [1] Accept: [application/stream+json]
没有内容
< 200 OK < 内容类型:[application/stream+json] < 传输编码:[分块] <日期:[2017 年 11 月 3 日星期五 09:42:53 GMT]
内容尚不可用
block 引用>
最佳答案
在此实例中,应用程序依赖于 spring-cloud-starter-eureka
,而后者本身又具有传递依赖于 spring-boot-starter-web
。
将 spring-boot-starter-web
添加到 Spring Boot 应用程序会将其变成 Spring MVC 应用程序,这解释了此行为。
关于java - Flux.error 即使抛出异常也会返回 200 http 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47092790/