Search in sources :

Example 1 with ElasticsearchStatusException

use of org.elasticsearch.ElasticsearchStatusException in project elasticsearch by elastic.

the class RemoteScrollableHitSourceTests method testWrapExceptionToPreserveStatus.

public void testWrapExceptionToPreserveStatus() throws IOException {
    Exception cause = new Exception();
    // Successfully get the status without a body
    RestStatus status = randomFrom(RestStatus.values());
    ElasticsearchStatusException wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(status.getStatus(), null, cause);
    assertEquals(status, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("No error body.", wrapped.getMessage());
    // Successfully get the status without a body
    HttpEntity okEntity = new StringEntity("test body", ContentType.TEXT_PLAIN);
    wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(status.getStatus(), okEntity, cause);
    assertEquals(status, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("body=test body", wrapped.getMessage());
    // Successfully get the status with a broken body
    IOException badEntityException = new IOException();
    HttpEntity badEntity = mock(HttpEntity.class);
    when(badEntity.getContent()).thenThrow(badEntityException);
    wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(status.getStatus(), badEntity, cause);
    assertEquals(status, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("Failed to extract body.", wrapped.getMessage());
    assertEquals(badEntityException, wrapped.getSuppressed()[0]);
    // Fail to get the status without a body
    int notAnHttpStatus = -1;
    assertNull(RestStatus.fromCode(notAnHttpStatus));
    wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(notAnHttpStatus, null, cause);
    assertEquals(RestStatus.INTERNAL_SERVER_ERROR, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("Couldn't extract status [" + notAnHttpStatus + "]. No error body.", wrapped.getMessage());
    // Fail to get the status without a body
    wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(notAnHttpStatus, okEntity, cause);
    assertEquals(RestStatus.INTERNAL_SERVER_ERROR, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("Couldn't extract status [" + notAnHttpStatus + "]. body=test body", wrapped.getMessage());
    // Fail to get the status with a broken body
    wrapped = RemoteScrollableHitSource.wrapExceptionToPreserveStatus(notAnHttpStatus, badEntity, cause);
    assertEquals(RestStatus.INTERNAL_SERVER_ERROR, wrapped.status());
    assertEquals(cause, wrapped.getCause());
    assertEquals("Couldn't extract status [" + notAnHttpStatus + "]. Failed to extract body.", wrapped.getMessage());
    assertEquals(badEntityException, wrapped.getSuppressed()[0]);
}
Also used : StringEntity(org.apache.http.entity.StringEntity) RestStatus(org.elasticsearch.rest.RestStatus) HttpEntity(org.apache.http.HttpEntity) IOException(java.io.IOException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) ContentTooLongException(org.apache.http.ContentTooLongException) ParsingException(org.elasticsearch.common.ParsingException) IOException(java.io.IOException) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException)

Example 2 with ElasticsearchStatusException

use of org.elasticsearch.ElasticsearchStatusException in project elasticsearch by elastic.

the class ReindexFromRemoteWithAuthTests method testReindexWithBadAuthentication.

public void testReindexWithBadAuthentication() throws Exception {
    ReindexRequestBuilder request = ReindexAction.INSTANCE.newRequestBuilder(client()).source("source").destination("dest").setRemoteInfo(newRemoteInfo("junk", "auth", emptyMap()));
    ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> request.get());
    assertThat(e.getMessage(), containsString("\"reason\":\"Bad Authorization\""));
}
Also used : ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException)

Example 3 with ElasticsearchStatusException

use of org.elasticsearch.ElasticsearchStatusException in project elasticsearch by elastic.

the class RestHighLevelClient method parseResponseException.

/**
     * Converts a {@link ResponseException} obtained from the low level REST client into an {@link ElasticsearchException}.
     * If a response body was returned, tries to parse it as an error returned from Elasticsearch.
     * If no response body was returned or anything goes wrong while parsing the error, returns a new {@link ElasticsearchStatusException}
     * that wraps the original {@link ResponseException}. The potential exception obtained while parsing is added to the returned
     * exception as a suppressed exception. This method is guaranteed to not throw any exception eventually thrown while parsing.
     */
ElasticsearchStatusException parseResponseException(ResponseException responseException) {
    Response response = responseException.getResponse();
    HttpEntity entity = response.getEntity();
    ElasticsearchStatusException elasticsearchException;
    if (entity == null) {
        elasticsearchException = new ElasticsearchStatusException(responseException.getMessage(), RestStatus.fromCode(response.getStatusLine().getStatusCode()), responseException);
    } else {
        try {
            elasticsearchException = parseEntity(entity, BytesRestResponse::errorFromXContent);
            elasticsearchException.addSuppressed(responseException);
        } catch (Exception e) {
            RestStatus restStatus = RestStatus.fromCode(response.getStatusLine().getStatusCode());
            elasticsearchException = new ElasticsearchStatusException("Unable to parse response body", restStatus, responseException);
            elasticsearchException.addSuppressed(e);
        }
    }
    return elasticsearchException;
}
Also used : GetResponse(org.elasticsearch.action.get.GetResponse) UpdateResponse(org.elasticsearch.action.update.UpdateResponse) IndexResponse(org.elasticsearch.action.index.IndexResponse) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) MainResponse(org.elasticsearch.action.main.MainResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) HttpEntity(org.apache.http.HttpEntity) RestStatus(org.elasticsearch.rest.RestStatus) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) ElasticsearchException(org.elasticsearch.ElasticsearchException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) IOException(java.io.IOException) ActionRequestValidationException(org.elasticsearch.action.ActionRequestValidationException)

Example 4 with ElasticsearchStatusException

use of org.elasticsearch.ElasticsearchStatusException in project elasticsearch by elastic.

the class BytesRestResponse method errorFromXContent.

public static ElasticsearchStatusException errorFromXContent(XContentParser parser) throws IOException {
    XContentParser.Token token = parser.nextToken();
    ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser::getTokenLocation);
    ElasticsearchException exception = null;
    RestStatus status = null;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        }
        if (STATUS.equals(currentFieldName)) {
            if (token != XContentParser.Token.FIELD_NAME) {
                ensureExpectedToken(XContentParser.Token.VALUE_NUMBER, token, parser::getTokenLocation);
                status = RestStatus.fromCode(parser.intValue());
            }
        } else {
            exception = ElasticsearchException.failureFromXContent(parser);
        }
    }
    if (exception == null) {
        throw new IllegalStateException("Failed to parse elasticsearch status exception: no exception was found");
    }
    ElasticsearchStatusException result = new ElasticsearchStatusException(exception.getMessage(), status, exception.getCause());
    for (String header : exception.getHeaderKeys()) {
        result.addHeader(header, exception.getHeader(header));
    }
    for (String metadata : exception.getMetadataKeys()) {
        result.addMetadata(metadata, exception.getMetadata(metadata));
    }
    return result;
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) XContentParser(org.elasticsearch.common.xcontent.XContentParser) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException)

Example 5 with ElasticsearchStatusException

use of org.elasticsearch.ElasticsearchStatusException in project elasticsearch by elastic.

the class BytesRestResponseTests method testErrorToAndFromXContent.

public void testErrorToAndFromXContent() throws IOException {
    final boolean detailed = randomBoolean();
    Exception original;
    ElasticsearchException cause = null;
    String reason;
    String type = "exception";
    RestStatus status = RestStatus.INTERNAL_SERVER_ERROR;
    boolean addHeadersOrMetadata = false;
    switch(randomIntBetween(0, 5)) {
        case 0:
            original = new ElasticsearchException("ElasticsearchException without cause");
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                reason = "ElasticsearchException without cause";
            } else {
                reason = "ElasticsearchException[ElasticsearchException without cause]";
            }
            break;
        case 1:
            original = new ElasticsearchException("ElasticsearchException with a cause", new FileNotFoundException("missing"));
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "exception";
                reason = "ElasticsearchException with a cause";
                cause = new ElasticsearchException("Elasticsearch exception [type=file_not_found_exception, reason=missing]");
            } else {
                reason = "ElasticsearchException[ElasticsearchException with a cause]";
            }
            break;
        case 2:
            original = new ResourceNotFoundException("ElasticsearchException with custom status");
            status = RestStatus.NOT_FOUND;
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "resource_not_found_exception";
                reason = "ElasticsearchException with custom status";
            } else {
                reason = "ResourceNotFoundException[ElasticsearchException with custom status]";
            }
            break;
        case 3:
            TransportAddress address = buildNewFakeTransportAddress();
            original = new RemoteTransportException("remote", address, "action", new ResourceAlreadyExistsException("ElasticsearchWrapperException with a cause that has a custom status"));
            status = RestStatus.BAD_REQUEST;
            if (detailed) {
                type = "resource_already_exists_exception";
                reason = "ElasticsearchWrapperException with a cause that has a custom status";
            } else {
                reason = "RemoteTransportException[[remote][" + address.toString() + "][action]]";
            }
            break;
        case 4:
            original = new RemoteTransportException("ElasticsearchWrapperException with a cause that has a special treatment", new IllegalArgumentException("wrong"));
            status = RestStatus.BAD_REQUEST;
            if (detailed) {
                type = "illegal_argument_exception";
                reason = "wrong";
            } else {
                reason = "RemoteTransportException[[ElasticsearchWrapperException with a cause that has a special treatment]]";
            }
            break;
        case 5:
            status = randomFrom(RestStatus.values());
            original = new ElasticsearchStatusException("ElasticsearchStatusException with random status", status);
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "status_exception";
                reason = "ElasticsearchStatusException with random status";
            } else {
                reason = "ElasticsearchStatusException[ElasticsearchStatusException with random status]";
            }
            break;
        default:
            throw new UnsupportedOperationException("Failed to generate random exception");
    }
    String message = "Elasticsearch exception [type=" + type + ", reason=" + reason + "]";
    ElasticsearchStatusException expected = new ElasticsearchStatusException(message, status, cause);
    if (addHeadersOrMetadata) {
        ElasticsearchException originalException = ((ElasticsearchException) original);
        if (randomBoolean()) {
            originalException.addHeader("foo", "bar", "baz");
            expected.addHeader("foo", "bar", "baz");
        }
        if (randomBoolean()) {
            originalException.addMetadata("es.metadata_0", "0");
            expected.addMetadata("es.metadata_0", "0");
        }
        if (randomBoolean()) {
            String resourceType = randomAsciiOfLength(5);
            String resourceId = randomAsciiOfLength(5);
            originalException.setResources(resourceType, resourceId);
            expected.setResources(resourceType, resourceId);
        }
        if (randomBoolean()) {
            originalException.setIndex("_index");
            expected.setIndex("_index");
        }
    }
    final XContentType xContentType = randomFrom(XContentType.values());
    Map<String, String> params = Collections.singletonMap("format", xContentType.mediaType());
    RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withParams(params).build();
    RestChannel channel = detailed ? new DetailedExceptionRestChannel(request) : new SimpleExceptionRestChannel(request);
    BytesRestResponse response = new BytesRestResponse(channel, original);
    ElasticsearchException parsedError;
    try (XContentParser parser = createParser(xContentType.xContent(), response.content())) {
        parsedError = BytesRestResponse.errorFromXContent(parser);
        assertNull(parser.nextToken());
    }
    assertEquals(expected.status(), parsedError.status());
    assertDeepEquals(expected, parsedError);
}
Also used : RemoteTransportException(org.elasticsearch.transport.RemoteTransportException) TransportAddress(org.elasticsearch.common.transport.TransportAddress) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) FileNotFoundException(java.io.FileNotFoundException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ElasticsearchException(org.elasticsearch.ElasticsearchException) Matchers.containsString(org.hamcrest.Matchers.containsString) ElasticsearchException(org.elasticsearch.ElasticsearchException) ParsingException(org.elasticsearch.common.ParsingException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) RemoteTransportException(org.elasticsearch.transport.RemoteTransportException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) XContentType(org.elasticsearch.common.xcontent.XContentType) FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Aggregations

ElasticsearchStatusException (org.elasticsearch.ElasticsearchStatusException)8 IOException (java.io.IOException)4 ElasticsearchException (org.elasticsearch.ElasticsearchException)3 RestStatus (org.elasticsearch.rest.RestStatus)3 HttpEntity (org.apache.http.HttpEntity)2 ParsingException (org.elasticsearch.common.ParsingException)2 XContentParser (org.elasticsearch.common.xcontent.XContentParser)2 FileNotFoundException (java.io.FileNotFoundException)1 ContentTooLongException (org.apache.http.ContentTooLongException)1 StringEntity (org.apache.http.entity.StringEntity)1 ResourceAlreadyExistsException (org.elasticsearch.ResourceAlreadyExistsException)1 ResourceNotFoundException (org.elasticsearch.ResourceNotFoundException)1 ActionRequestValidationException (org.elasticsearch.action.ActionRequestValidationException)1 BulkResponse (org.elasticsearch.action.bulk.BulkResponse)1 DeleteResponse (org.elasticsearch.action.delete.DeleteResponse)1 GetResponse (org.elasticsearch.action.get.GetResponse)1 IndexResponse (org.elasticsearch.action.index.IndexResponse)1 MainResponse (org.elasticsearch.action.main.MainResponse)1 SearchPhaseExecutionException (org.elasticsearch.action.search.SearchPhaseExecutionException)1 UpdateResponse (org.elasticsearch.action.update.UpdateResponse)1