本文介绍了如何使用Micronaut客户端注释映射errorType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Micronaut客户端注释来映射errorType,以编程方式提供成功或失败情况下,我们可以提供主体类型和errorType对象.
How to map errorType using Micronaut client annotation, In case of programatically we can provide body type and errorType objects in case of success and failure.
以编程方式调用客户端:
Programmatically calling client:
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 ) {
}
}
}
使用注释呼叫客户端
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();
}
推荐答案
根据Micronaut API文档,@ Client注释提供了errorType,它对我来说可以处理errorType响应.
As per the Micronaut API doc, errorType available with @Client annotation, it worked for me to handle the errorType response.
https://docs.micronaut.io/latest/api/index.html https://docs.micronaut.io/latest/guide/index.html#clientAnnotation
@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=Object.class,//The type used to decode errors
configuration=<? extends HttpClientConfiguration>//The http client configuration bean to use
)
@Header(name="", value="")
public interface TestClient {
@Get("?id=123")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Single<HttpResponse<User>> getUser();
}
这篇关于如何使用Micronaut客户端注释映射errorType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!