繁体   English   中英

即使抛出异常,Flux.error也会返回200个http代码

[英]Flux.error return 200 http code even if exception is thrown

我使用spring-boot(v2 M3)和spring-webflux开展项目。 在编写功能时,我看到我的微服务返回了一个Http 200状态代码,同时在通量中返回错误。

所以,我做了一个简单的测试:我创建了一个简单的控制器

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

因此,我的测试失败,因为我的控制器返回错误通量返回200状态代码而不是503状态代码(在我的控制台中可以很好地跟踪异常日志“test”)。 你知道为什么吗 ?

java.lang.AssertionError:预期响应状态值200的范围:但是:

GET http:// localhost:54432 / test / errors WebTestClient-Request-Id:[1]接受:[application / stream + json]

无内容

<200 OK <Content-Type:[application / stream + json] <Transfer-Encoding:[chunked] <Date:[Fri,03 Nov 2017 09:42:53 GMT]

内容尚不可用

在这个例子中,应用程序依赖于spring-cloud-starter-eureka ,它本身对spring-boot-starter-web具有传递依赖性。

spring-boot-starter-web到Spring Boot应用程序会将其转换为Spring MVC应用程序,这解释了这种行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM