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]);
}
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\""));
}
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;
}
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;
}
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);
}
Aggregations