Search in sources :

Example 1 with RestStatusException

use of org.springframework.data.elasticsearch.RestStatusException in project spring-data-elasticsearch by spring-projects.

the class DefaultReactiveElasticsearchClient method contentOrError.

/**
 * checks if the given content body contains an {@link ElasticsearchException}, if yes it is returned in a Mono.error.
 * Otherwise the content is returned in the Mono
 *
 * @param content the content to analyze
 * @param mediaType the returned media type
 * @param status the response status
 * @return a Mono with the content or an Mono.error
 */
private static Mono<String> contentOrError(String content, String mediaType, RestStatus status) {
    ElasticsearchException exception = getElasticsearchException(content, mediaType, status);
    if (exception != null) {
        StringBuilder sb = new StringBuilder();
        buildExceptionMessages(sb, exception);
        return Mono.error(new RestStatusException(status.getStatus(), sb.toString(), exception));
    }
    return Mono.just(content);
}
Also used : UncategorizedElasticsearchException(org.springframework.data.elasticsearch.UncategorizedElasticsearchException) ElasticsearchException(org.elasticsearch.ElasticsearchException) RestStatusException(org.springframework.data.elasticsearch.RestStatusException)

Example 2 with RestStatusException

use of org.springframework.data.elasticsearch.RestStatusException in project spring-data-elasticsearch by spring-projects.

the class DefaultReactiveElasticsearchClientTest method shouldThrowRestStatusExceptionOnServer5xxWithEmptyBody.

// #1712
@Test
@DisplayName("should throw RestStatusException on server 5xx with empty body")
void shouldThrowRestStatusExceptionOnServer5xxWithEmptyBody() {
    when(hostProvider.getActive(any())).thenReturn(Mono.just(webClient));
    WebClient.RequestBodyUriSpec requestBodyUriSpec = mock(WebClient.RequestBodyUriSpec.class);
    when(requestBodyUriSpec.uri((Function<UriBuilder, URI>) any())).thenReturn(requestBodyUriSpec);
    when(requestBodyUriSpec.attribute(any(), any())).thenReturn(requestBodyUriSpec);
    when(requestBodyUriSpec.headers(any())).thenReturn(requestBodyUriSpec);
    when(webClient.method(any())).thenReturn(requestBodyUriSpec);
    when(requestBodyUriSpec.exchangeToMono(any())).thenAnswer(invocationOnMock -> {
        Function<ClientResponse, ? extends Mono<?>> responseHandler = invocationOnMock.getArgument(0);
        ClientResponse clientResponse = mock(ClientResponse.class);
        when(clientResponse.statusCode()).thenReturn(HttpStatus.SERVICE_UNAVAILABLE);
        ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
        when(headers.contentType()).thenReturn(Optional.empty());
        when(clientResponse.headers()).thenReturn(headers);
        when(clientResponse.body(any())).thenReturn(Mono.empty());
        return responseHandler.apply(clientResponse);
    });
    ReactiveElasticsearchClient client = new DefaultReactiveElasticsearchClient(hostProvider, requestCreator);
    // 
    client.get(new GetRequest("42")).as(// 
    StepVerifier::create).expectError(// 
    RestStatusException.class).verify();
}
Also used : ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) GetRequest(org.elasticsearch.action.get.GetRequest) UriBuilder(org.springframework.web.util.UriBuilder) StepVerifier(reactor.test.StepVerifier) RestStatusException(org.springframework.data.elasticsearch.RestStatusException) WebClient(org.springframework.web.reactive.function.client.WebClient) URI(java.net.URI) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName)

Example 3 with RestStatusException

use of org.springframework.data.elasticsearch.RestStatusException in project spring-data-elasticsearch by spring-projects.

the class ElasticsearchExceptionTranslator method isSeqNoConflict.

private boolean isSeqNoConflict(Exception exception) {
    Integer status = null;
    String message = null;
    if (exception instanceof ElasticsearchStatusException) {
        ElasticsearchStatusException statusException = (ElasticsearchStatusException) exception;
        status = statusException.status().getStatus();
        message = statusException.getMessage();
    }
    if (exception instanceof RestStatusException) {
        RestStatusException statusException = (RestStatusException) exception;
        status = statusException.getStatus();
        message = statusException.getMessage();
    }
    if (status != null && message != null) {
        return status == 409 && message.contains("type=version_conflict_engine_exception") && message.contains("version conflict, required seqNo");
    }
    if (exception instanceof VersionConflictEngineException) {
        VersionConflictEngineException versionConflictEngineException = (VersionConflictEngineException) exception;
        return versionConflictEngineException.getMessage() != null && versionConflictEngineException.getMessage().contains("version conflict, required seqNo");
    }
    return false;
}
Also used : VersionConflictEngineException(org.elasticsearch.index.engine.VersionConflictEngineException) RestStatusException(org.springframework.data.elasticsearch.RestStatusException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException)

Example 4 with RestStatusException

use of org.springframework.data.elasticsearch.RestStatusException in project spring-data-elasticsearch by spring-projects.

the class ElasticsearchExceptionTranslator method translateExceptionIfPossible.

@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
    if (isSeqNoConflict(ex)) {
        return new OptimisticLockingFailureException("Cannot index a document due to seq_no+primary_term conflict", ex);
    }
    if (ex instanceof ElasticsearchException) {
        ElasticsearchException elasticsearchException = (ElasticsearchException) ex;
        if (!indexAvailable(elasticsearchException)) {
            return new NoSuchIndexException(ObjectUtils.nullSafeToString(elasticsearchException.getMetadata("es.index")), ex);
        }
        if (elasticsearchException instanceof ElasticsearchStatusException) {
            ElasticsearchStatusException elasticsearchStatusException = (ElasticsearchStatusException) elasticsearchException;
            return new RestStatusException(elasticsearchStatusException.status().getStatus(), elasticsearchStatusException.getMessage(), elasticsearchStatusException);
        }
        return new UncategorizedElasticsearchException(ex.getMessage(), ex);
    }
    if (ex instanceof RestStatusException) {
        RestStatusException restStatusException = (RestStatusException) ex;
        Throwable cause = restStatusException.getCause();
        if (cause instanceof ElasticsearchException) {
            ElasticsearchException elasticsearchException = (ElasticsearchException) cause;
            if (!indexAvailable(elasticsearchException)) {
                return new NoSuchIndexException(ObjectUtils.nullSafeToString(elasticsearchException.getMetadata("es.index")), ex);
            }
        }
    }
    if (ex instanceof ValidationException) {
        return new DataIntegrityViolationException(ex.getMessage(), ex);
    }
    Throwable cause = ex.getCause();
    if (cause instanceof IOException) {
        return new DataAccessResourceFailureException(ex.getMessage(), ex);
    }
    return null;
}
Also used : OptimisticLockingFailureException(org.springframework.dao.OptimisticLockingFailureException) ValidationException(org.elasticsearch.common.ValidationException) DataAccessResourceFailureException(org.springframework.dao.DataAccessResourceFailureException) NoSuchIndexException(org.springframework.data.elasticsearch.NoSuchIndexException) UncategorizedElasticsearchException(org.springframework.data.elasticsearch.UncategorizedElasticsearchException) ElasticsearchException(org.elasticsearch.ElasticsearchException) UncategorizedElasticsearchException(org.springframework.data.elasticsearch.UncategorizedElasticsearchException) IOException(java.io.IOException) RestStatusException(org.springframework.data.elasticsearch.RestStatusException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException)

Example 5 with RestStatusException

use of org.springframework.data.elasticsearch.RestStatusException in project spring-data-elasticsearch by spring-projects.

the class DefaultReactiveElasticsearchClient method handleServerError.

// endregion
// region error and exception handling
private <T> Publisher<? extends T> handleServerError(Request request, ClientResponse response) {
    int statusCode = response.statusCode().value();
    RestStatus status = RestStatus.fromCode(statusCode);
    String mediaType = response.headers().contentType().map(MediaType::toString).orElse(XContentType.JSON.mediaType());
    return // 
    response.body(BodyExtractors.toMono(byte[].class)).switchIfEmpty(Mono.error(new RestStatusException(status.getStatus(), String.format("%s request to %s returned error code %s and no body.", request.getMethod(), request.getEndpoint(), statusCode)))).map(// 
    bytes -> new String(bytes, StandardCharsets.UTF_8)).flatMap(content -> contentOrError(content, mediaType, status)).flatMap(unused -> Mono.error(new RestStatusException(status.getStatus(), String.format("%s request to %s returned error code %s.", request.getMethod(), request.getEndpoint(), statusCode))));
}
Also used : SSLContext(javax.net.ssl.SSLContext) SearchHits(org.elasticsearch.search.SearchHits) TaskSubmissionResponse(org.elasticsearch.client.tasks.TaskSubmissionResponse) RequestBodySpec(org.springframework.web.reactive.function.client.WebClient.RequestBodySpec) ClientConfiguration(org.springframework.data.elasticsearch.client.ClientConfiguration) ClientAuth(io.netty.handler.ssl.ClientAuth) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) Duration(java.time.Duration) ApplicationProtocolConfig(io.netty.handler.ssl.ApplicationProtocolConfig) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) JdkSslContext(io.netty.handler.ssl.JdkSslContext) GetSettingsResponse(org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) IndicesAliasesRequest(org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest) StandardCharsets(java.nio.charset.StandardCharsets) DeleteIndexTemplateRequest(org.elasticsearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) XContentType(org.elasticsearch.xcontent.XContentType) BodyExtractors(org.springframework.web.reactive.function.BodyExtractors) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) RestStatus(org.elasticsearch.rest.RestStatus) HttpClient(reactor.netty.http.client.HttpClient) ChannelOption(io.netty.channel.ChannelOption) Suggest(org.elasticsearch.search.suggest.Suggest) Cluster(org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient.Cluster) ClearScrollRequest(org.elasticsearch.action.search.ClearScrollRequest) NamedXContents(org.springframework.data.elasticsearch.client.util.NamedXContents) GetResult(org.elasticsearch.index.get.GetResult) SearchRequest(org.elasticsearch.action.search.SearchRequest) Supplier(java.util.function.Supplier) NamedXContentRegistry(org.elasticsearch.xcontent.NamedXContentRegistry) ProxyProvider(reactor.netty.transport.ProxyProvider) ByQueryResponse(org.springframework.data.elasticsearch.core.query.ByQueryResponse) RefreshRequest(org.elasticsearch.action.admin.indices.refresh.RefreshRequest) ConnectException(java.net.ConnectException) Aggregation(org.elasticsearch.search.aggregations.Aggregation) Nullable(org.springframework.lang.Nullable) FlushResponse(org.elasticsearch.action.admin.indices.flush.FlushResponse) MainRequest(org.elasticsearch.action.main.MainRequest) ReactorClientHttpConnector(org.springframework.http.client.reactive.ReactorClientHttpConnector) Publisher(org.reactivestreams.Publisher) ObjectUtils(org.springframework.util.ObjectUtils) HttpMethod(org.springframework.http.HttpMethod) Mono(reactor.core.publisher.Mono) IOException(java.io.IOException) ResponseConverter(org.springframework.data.elasticsearch.core.ResponseConverter) Request(org.elasticsearch.client.Request) Flux(reactor.core.publisher.Flux) CloseIndexRequest(org.elasticsearch.action.admin.indices.close.CloseIndexRequest) SearchScrollRequest(org.elasticsearch.action.search.SearchScrollRequest) UncategorizedElasticsearchException(org.springframework.data.elasticsearch.UncategorizedElasticsearchException) ElasticsearchException(org.elasticsearch.ElasticsearchException) GetResponse(org.elasticsearch.action.get.GetResponse) ScrollState(org.springframework.data.elasticsearch.client.util.ScrollState) RestStatusException(org.springframework.data.elasticsearch.RestStatusException) WebClient(org.springframework.web.reactive.function.client.WebClient) SearchTemplateRequest(org.elasticsearch.script.mustache.SearchTemplateRequest) EntityUtils(org.apache.http.util.EntityUtils) DeprecationHandler(org.elasticsearch.xcontent.DeprecationHandler) SearchResponse(org.elasticsearch.action.search.SearchResponse) DeleteByQueryRequest(org.elasticsearch.index.reindex.DeleteByQueryRequest) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) Method(java.lang.reflect.Method) TimeValue(org.elasticsearch.core.TimeValue) SearchHit(org.elasticsearch.search.SearchHit) GetRequest(org.elasticsearch.action.get.GetRequest) MultiGetResponse(org.elasticsearch.action.get.MultiGetResponse) NoReachableHostException(org.springframework.data.elasticsearch.client.NoReachableHostException) HttpHeaders(org.springframework.http.HttpHeaders) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) Collection(java.util.Collection) GetAliasesRequest(org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest) MediaType(org.springframework.http.MediaType) MultiGetItemResponse(org.elasticsearch.action.get.MultiGetItemResponse) Verification(org.springframework.data.elasticsearch.client.reactive.HostProvider.Verification) InetSocketAddress(java.net.InetSocketAddress) MainResponse(org.elasticsearch.action.main.MainResponse) ElasticsearchHost(org.springframework.data.elasticsearch.client.ElasticsearchHost) Entry(java.util.Map.Entry) Optional(java.util.Optional) GetSettingsRequest(org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest) ClientLogger(org.springframework.data.elasticsearch.client.ClientLogger) IdentityCipherSuiteFilter(io.netty.handler.ssl.IdentityCipherSuiteFilter) org.elasticsearch.client.indices(org.elasticsearch.client.indices) MultiGetRequest(org.elasticsearch.action.get.MultiGetRequest) Function(java.util.function.Function) OpenIndexRequest(org.elasticsearch.action.admin.indices.open.OpenIndexRequest) ClearScrollResponse(org.elasticsearch.action.search.ClearScrollResponse) GetAliasesResponse(org.elasticsearch.client.GetAliasesResponse) IndexResponse(org.elasticsearch.action.index.IndexResponse) XContentParser(org.elasticsearch.xcontent.XContentParser) UpdateByQueryRequest(org.elasticsearch.index.reindex.UpdateByQueryRequest) BulkByScrollResponse(org.elasticsearch.index.reindex.BulkByScrollResponse) SearchTemplateResponse(org.elasticsearch.script.mustache.SearchTemplateResponse) WriteTimeoutHandler(io.netty.handler.timeout.WriteTimeoutHandler) DeleteIndexRequest(org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) Lazy(org.springframework.data.util.Lazy) TimeUnit(java.util.concurrent.TimeUnit) Indices(org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient.Indices) FlushRequest(org.elasticsearch.action.admin.indices.flush.FlushRequest) ReflectionUtils(org.springframework.util.ReflectionUtils) RefreshResponse(org.elasticsearch.action.admin.indices.refresh.RefreshResponse) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) ReindexRequest(org.elasticsearch.index.reindex.ReindexRequest) Assert(org.springframework.util.Assert) RestStatus(org.elasticsearch.rest.RestStatus) RestStatusException(org.springframework.data.elasticsearch.RestStatusException)

Aggregations

RestStatusException (org.springframework.data.elasticsearch.RestStatusException)5 ElasticsearchException (org.elasticsearch.ElasticsearchException)3 ElasticsearchStatusException (org.elasticsearch.ElasticsearchStatusException)3 UncategorizedElasticsearchException (org.springframework.data.elasticsearch.UncategorizedElasticsearchException)3 IOException (java.io.IOException)2 ChannelOption (io.netty.channel.ChannelOption)1 ApplicationProtocolConfig (io.netty.handler.ssl.ApplicationProtocolConfig)1 ClientAuth (io.netty.handler.ssl.ClientAuth)1 IdentityCipherSuiteFilter (io.netty.handler.ssl.IdentityCipherSuiteFilter)1 JdkSslContext (io.netty.handler.ssl.JdkSslContext)1 ReadTimeoutHandler (io.netty.handler.timeout.ReadTimeoutHandler)1 WriteTimeoutHandler (io.netty.handler.timeout.WriteTimeoutHandler)1 Method (java.lang.reflect.Method)1 ConnectException (java.net.ConnectException)1 InetSocketAddress (java.net.InetSocketAddress)1 URI (java.net.URI)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Duration (java.time.Duration)1 Collection (java.util.Collection)1 Entry (java.util.Map.Entry)1