Как сопоставить errorType с помощью аннотации клиента Micronaut

Как сопоставить errorType с помощью клиентской аннотации Micronaut. В случае программного обеспечения мы можем предоставить тип тела и объекты 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 ) {              
        } 
    }
}

Вызов клиента с использованием аннотаций

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

person 2787184    schedule 16.09.2019    source источник


Ответы (2)


Если вы хотите определить свой собственный объект как 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 генерирует исключение HttpClientResponseException для кода HTTP (400 и выше 400 (кроме 404)) в случае исключения из базового клиента. Таким образом, если базовый клиент предоставляет настраиваемый объект ошибки в случае исключения в качестве тела ответа, этот настраиваемый тип ошибки можно использовать для корректной обработки ошибок и ведения журнала.

Аналогичный подход можно использовать и для DefaultHttpClient.

person Mohit Gupta    schedule 08.10.2019

Согласно документу API Micronaut, errorType доступен с аннотацией @Client, мне удалось обработать ответ errorType.

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();
   }
person 2787184    schedule 18.09.2019