gpt4 book ai didi

java - 如何使用 Micronaut 客户端注释映射 errorType

转载 作者:行者123 更新时间:2023-12-02 09:31:09 30 4
gpt4 key购买 nike

如何使用 Micronaut 客户端注释映射 errorType,如果以编程方式,我们可以在成功和失败时提供主体类型和 errorType 对象。

以编程方式调用客户端:

import io.micronaut.core.type.Argument;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.client.DefaultHttpClient;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.http.uri.UriBuilder;
import io.reactivex.Single;
import java.net.URL;

@Singleton
public class Test{
public User getUser(String id) {
try {
String uriPath = UriBuilder.of("url")
.queryParam("id", id)
.toString();

DefaultHttpClient httpClient = new DefaultHttpClient(new URL(""),httpClientConfiguration);

Single<HttpResponse<User>> single = Single.fromPublisher(httpClient.exchange(
HttpRequest.GET(uriPath).header(X_REQUEST_ID, REQUEST_ID).accept(MediaType.APPLICATION_JSON_TYPE),
Argument.of(User.class), //bodyType
Argument.of(Object.class) //errorType
));

HttpResponse<User> response = single.blockingGet();
User user = response.body();
return user;
} catch (HttpClientResponseException | Exception e ) {
}
}
}

使用注解调用Client

import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Consumes;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Header;
import io.micronaut.http.client.annotation.Client;
import io.reactivex.Single;
@Client(value = "url",
path = "/user")
public interface TestClient {
@Get("?id=123")
@Consumes(MediaType.APPLICATION_JSON)
Single<HttpResponse<User>> getUser();
}

最佳答案

如果你想定义自己的自定义对象为errorType,可以在micronaut中使用声明式客户端时声明如下:

@Client(id="",//The ID of the client
value = "url", //The URL or service ID of the remote service
path = "/user",//The base URI for the client. Only to be used in conjunction with id().
errorType=YourCustomObject.class,//The type used to decode errors
configuration=<? extends HttpClientConfiguration>//The http client configuration bean to use
)
public interface ExternalCallClient{
//some API method
}

然后在您的连接器客户端类:

class Connect{

@Inject
private ExternalCallClient externalCallClient;

call(){

try{
//call to external API method using externalCallClient
}catch(HttpClientResponseException e){

Optional<YourCustomObject> error = e.getResponse()
.getBody(YourCustomObject.class)
}
}
}

如果底层客户端出现异常,Micronaut 客户端会对 HTTP 代码(400 及以上 400(404 除外))抛出 HttpClientResponseException。因此,如果底层客户端在出现异常时提供自定义错误对象作为响应正文,则此自定义错误类型可用于优雅的错误处理和日志记录。

类似的方法也可用于 DefaultHttpClient。

关于java - 如何使用 Micronaut 客户端注释映射 errorType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57957323/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com