groovy 在Micronaut版本3.7.3中未应用声明性客户端的ClientConfiguration中的exceptionOnErrorStatus

bvjxkvbb  于 2022-11-21  发布在  其他
关注(0)|答案(1)|浏览(120)

我已经为我的Declarative HttpClient提供了一个配置类,以强制在出错时抛出异常(状态〉400),或者我可能误解了exceptionOnErrorStatus配置选项。

@Client(value = "/", configuration = ApiClientConfiguration)
interface Api {
    @Get("/author/{id}")
    AuthorResource getAuthor(Long id, @Header(name="Authorization") String authorization)
}

下面是配置类

@ConfigurationProperties("httpclient.api")
class ApiClientConfiguration extends DefaultHttpClientConfiguration {
    @Override
    boolean isExceptionOnErrorStatus() {
        return true
    }
}

我的@MicronautTest应该抛出异常,但它没有:

def "It fails to get an non-existing Author"() {
        given:
        def token = viewer()

        when:
        //This commented code throws an exception as expected
/*
        def author = client.toBlocking().exchange(HttpRequest.create(
                HttpMethod.GET,
                "/author/${badId}"
        ).bearerAuth(token))
*/
        //This does not despite the provided HttpClientConfiguration
        def author = api.getAuthor(badId, bearerAuth(token))

        then:
        def ex = thrown(HttpClientResponseException)
        ex.status == NOT_FOUND
        ex.getResponse().getBody(ErrorResource).map {
            assert it.message == "Author with id ${badId} not found."
            it
        }.isPresent()

        where:
        badId = anyInt()
    }

感谢您的帮助。我不习惯配置类,所以我可能在使用它的方式上有错误,另一种可能是exceptionOnErrorStatus并不意味着我认为它的意思。我已经检查了文档,我认为它是,虽然。

20jt8wwn

20jt8wwn1#

它看起来像是使用了Configuration类,调用了方法isExceptionOnErrorStatus(),但它没有像我想象的那样被解释。
结论,当你使用一个声明式客户端,并且想要测试status〉400时的响应时,让你的接口返回一个HttpResponse<X>

@Get("/author/{id}")
    HttpResponse<AuthorResource> getAuthor(Long id, @Header(name = "Authorization") String authorization)

该行为与引发异常的低级客户端不同。
修改测试:

def response = api.getAuthor(badId, bearerAuth(token))
        response.status == NOT_FOUND
        response.getBody(ErrorResponse).map {
            assert it.message == "Author with id ${badId} not found."
            it
        }.isPresent()

相关问题