Как обработать 200 кодов состояния с помощью шаблона ответа на ошибку? - PullRequest
0 голосов
/ 26 апреля 2020

Я хочу обработать 200 с ответом об ошибке

final ResponseEntity<ResponseType> responseEntity = restTemplate.postForEntity(url, requestEntity, ResponseType.class);

Здесь я непосредственно использую объект модели ответа в шаблоне покоя, и ниже мой блок catch

catch (final RestClientException | HttpMessageConversionException ex) {
                throw new CustomException(message, ex);
            }

Здесь я добавил HttpMessageConversionException, потому что я получаю 200 с ответом об ошибке, и при преобразовании этого в мой класс типа ответа об успехе в шаблоне rest он выдает, потому что в моем конструкторе класса ответа об успехе есть проверка поля.

ниже мой класс ответа, используемый в шаблоне отдыха

@JsonDeserialize(builder = ResponseType.Builder.class)
@JacksonXmlRootElement(localName = "Test")
public class ResponseType {

    private final String details;

    private ResponseType(final Builder builder) {
        this.details = OptionalCheck.checkPresent(builder.details, "details");
    }

    public static Builder builder() {
        return new Builder();
    }

    //getter

    public static final class Builder {
        private Optional<String> details = Optional.empty();

        @JacksonXmlProperty(localName = "details")
        public Builder withDetails(final String theDetails) {
            this.details = Optional.ofNullable(theDetails);
            return this;
        }


        public ResponseType build() {
            return new ResponseType(this);
        }
    }
}

, ниже - трассировка стека

org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class com.test.ResponseType$Builder]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.test.ResponseType$Builder`, problem: details must be present.
 at [Source: (ByteArrayInputStream); line: 5, column: 1]
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:242)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:227)
    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:102)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:994)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:977)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:737)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670)
    at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:445)

    Caused by: java.lang.IllegalArgumentException: details must be present.
    at com.test.OptionalCheck.lambda$checkPresent$0(OptionalCheck.java:46)
    at java.base/java.util.Optional.orElseThrow(Optional.java:408)

Есть ли другой способ справиться с этим?

1 Ответ

0 голосов
/ 26 апреля 2020

Для лучшей помощи, вы должны показать нам пример хорошего ответа и ответа об ошибке.

Но я приведу пример того, как вы должны это сделать.

Давайте скажем, хороший ответ выглядит так:

{
    "details": {
        ...
    }
}

, а ответ об ошибке выглядит следующим образом:

{
    "error": {
        ...
    }
}

Затем вы должны определить тип ответа как класс с 2 полями: details и error, затем проверьте наличие и отреагируйте, если необходимо, например,

DetailsOrErrorResponse response = restTemplate.getForObject(url, DetailsOrErrorResponse.class);
if (response.getError() != null) {
    // handle error here
} else if (response.getDetails() == null) {
    throw new IllegalArgumentException("Invalid response: Missing `details` or `error`");
} else {
    // handle good response here
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...