Search in sources :

Example 1 with CouchbaseException

use of com.couchbase.client.core.error.CouchbaseException in project couchbase-jdbc-driver by couchbaselabs.

the class ConnectionHandle method rawAnalyticsQuery.

/**
 * Sends a raw analytics query, allows to be used where the regular API does not suffice.
 * <p>
 * It should really only be used if the primary query API cannot be used for some reason.
 *
 * @param method the http method to use.
 * @param path the http path to execute.
 * @param headers the optional http headers to send.
 * @param content the optional payload to send.
 * @param timeout the timeout to use.
 * @return the core response to use.
 * @throws SQLException in case the query failed.
 */
public CoreHttpResponse rawAnalyticsQuery(HttpMethod method, String path, Map<String, Object> headers, byte[] content, Duration timeout) throws SQLException {
    CoreHttpClient client = cluster.core().httpClient(RequestTarget.analytics());
    CoreCommonOptions options = CoreCommonOptions.of(timeout == null || timeout.isZero() ? null : timeout, null, null);
    CoreHttpRequest.Builder builder;
    switch(method) {
        case GET:
            builder = client.get(path(path), options);
            break;
        case DELETE:
            builder = client.delete(path(path), options);
            break;
        case POST:
            builder = client.post(path(path), options);
            if (content != null) {
                builder = builder.json(content);
            }
            break;
        default:
            throw new IllegalStateException("Unsupported http verb: " + method);
    }
    if (headers != null) {
        for (Map.Entry<String, Object> header : headers.entrySet()) {
            builder = builder.header(header.getKey(), header.getValue());
        }
    }
    try {
        return builder.build().exec(cluster.core()).get();
    } catch (ExecutionException ex) {
        if (ex.getCause() instanceof CouchbaseException) {
            String ctx = ((CouchbaseException) ex.getCause()).context().exportAsString(Context.ExportFormat.JSON);
            throw new SQLException("Failed to perform analytics query: " + ctx, ex);
        } else {
            throw new SQLException("Failed to perform analytics query - cause: " + ex.getMessage(), ex);
        }
    } catch (Exception ex) {
        throw new SQLException("Failed to perform analytics query - cause: " + ex.getMessage(), ex);
    }
}
Also used : CoreHttpRequest(com.couchbase.client.core.endpoint.http.CoreHttpRequest) SQLException(java.sql.SQLException) CoreHttpClient(com.couchbase.client.core.endpoint.http.CoreHttpClient) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) ExecutionException(java.util.concurrent.ExecutionException) SQLException(java.sql.SQLException) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) CoreCommonOptions(com.couchbase.client.core.endpoint.http.CoreCommonOptions) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map)

Example 2 with CouchbaseException

use of com.couchbase.client.core.error.CouchbaseException in project couchbase-jvm-clients by couchbase.

the class ErrorMapLoadingHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    Optional<Duration> latency = ConnectTimings.stop(ctx.channel(), this.getClass(), false);
    if (msg instanceof ByteBuf) {
        if (successful((ByteBuf) msg)) {
            Optional<ErrorMap> loadedMap = extractErrorMap((ByteBuf) msg);
            loadedMap.ifPresent(errorMap -> ctx.channel().attr(ChannelAttributes.ERROR_MAP_KEY).set(errorMap));
            endpointContext.environment().eventBus().publish(new ErrorMapLoadedEvent(ioContext, latency.orElse(Duration.ZERO), loadedMap));
        } else {
            endpointContext.environment().eventBus().publish(new ErrorMapLoadingFailedEvent(ioContext, latency.orElse(Duration.ZERO), status((ByteBuf) msg)));
        }
        interceptedConnectPromise.trySuccess();
        ctx.pipeline().remove(this);
    } else {
        interceptedConnectPromise.tryFailure(new CouchbaseException("Unexpected response " + "type on channel read, this is a bug - please report. " + msg));
    }
    ReferenceCountUtil.release(msg);
}
Also used : CouchbaseException(com.couchbase.client.core.error.CouchbaseException) Duration(java.time.Duration) ErrorMapLoadingFailedEvent(com.couchbase.client.core.cnc.events.io.ErrorMapLoadingFailedEvent) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf) ErrorMapLoadedEvent(com.couchbase.client.core.cnc.events.io.ErrorMapLoadedEvent)

Example 3 with CouchbaseException

use of com.couchbase.client.core.error.CouchbaseException in project couchbase-jvm-clients by couchbase.

the class FeatureNegotiatingHandler method channelRead.

/**
 * As soon as we get a response, turn it into a list of negotiated server features.
 *
 * <p>Since the server might respond with a non-success status code, this case is handled
 * and we would move on without any negotiated features but make sure the proper event
 * is raised.</p>
 *
 * @param ctx the {@link ChannelHandlerContext} for which the channel read operation is made.
 * @param msg the incoming msg that needs to be parsed.
 */
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    if (msg instanceof ByteBuf) {
        Optional<Duration> latency = ConnectTimings.stop(ctx.channel(), this.getClass(), false);
        if (!successful((ByteBuf) msg)) {
            endpointContext.environment().eventBus().publish(new FeaturesNegotiationFailedEvent(ioContext, status((ByteBuf) msg)));
        }
        Set<ServerFeature> negotiated = extractFeaturesFromBody((ByteBuf) msg);
        ctx.channel().attr(ChannelAttributes.SERVER_FEATURE_KEY).set(negotiated);
        endpointContext.environment().eventBus().publish(new FeaturesNegotiatedEvent(ioContext, latency.orElse(Duration.ZERO), new ArrayList<>(negotiated)));
        interceptedConnectPromise.trySuccess();
        ctx.pipeline().remove(this);
    } else {
        interceptedConnectPromise.tryFailure(new CouchbaseException("Unexpected response " + "type on channel read, this is a bug - please report. " + msg));
    }
    ReferenceCountUtil.release(msg);
}
Also used : FeaturesNegotiationFailedEvent(com.couchbase.client.core.cnc.events.io.FeaturesNegotiationFailedEvent) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) ArrayList(java.util.ArrayList) Duration(java.time.Duration) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf) FeaturesNegotiatedEvent(com.couchbase.client.core.cnc.events.io.FeaturesNegotiatedEvent)

Example 4 with CouchbaseException

use of com.couchbase.client.core.error.CouchbaseException in project couchbase-jvm-clients by couchbase.

the class QueryChunkResponseParser method errorsToThrowable.

static CouchbaseException errorsToThrowable(final byte[] bytes, HttpResponse header, RequestContext ctx) {
    int httpStatus = header != null ? header.status().code() : 0;
    final List<ErrorCodeAndMessage> errors = bytes.length == 0 ? Collections.emptyList() : ErrorCodeAndMessage.fromJsonArray(bytes);
    QueryErrorContext errorContext = new QueryErrorContext(ctx, errors, httpStatus);
    if (errors.size() >= 1) {
        ErrorCodeAndMessage codeAndMessage = errors.get(0);
        int code = codeAndMessage.code();
        String message = codeAndMessage.message();
        int reasonCode = codeAndMessage.reason() != null ? (int) codeAndMessage.reason().getOrDefault("code", 0) : 0;
        if (code == 3000) {
            return new ParsingFailureException(errorContext);
        } else if (PREPARED_ERROR_CODES.contains(code)) {
            return new PreparedStatementFailureException(errorContext, RETRYABLE_PREPARED_ERROR_CODES.contains(code));
        } else if (code == 4300 && message.matches("^.*index .*already exist.*")) {
            return new IndexExistsException(errorContext);
        } else if (code >= 4000 && code < 5000) {
            return new PlanningFailureException(errorContext);
        } else if (code == 12004 || code == 12016 || (code == 5000 && message.matches("^.*index .+ not found.*"))) {
            return new IndexNotFoundException(errorContext);
        } else if (code == 5000 && message.matches("^.*Index .*already exist.*")) {
            return new IndexExistsException(errorContext);
        } else if (code == 5000 && message.contains("limit for number of indexes that can be created per scope has been reached")) {
            return new QuotaLimitedException(errorContext);
        } else if (code >= 5000 && code < 6000) {
            return new InternalServerFailureException(errorContext);
        } else if (code == 12009) {
            if (message.contains("CAS mismatch") || reasonCode == 12033) {
                return new CasMismatchException(errorContext);
            } else if (reasonCode == 17014) {
                return new DocumentNotFoundException(errorContext);
            } else if (reasonCode == 17012) {
                return new DocumentExistsException(errorContext);
            } else {
                return new DmlFailureException(errorContext);
            }
        } else if ((code >= 10000 && code < 11000) || code == 13014) {
            return new AuthenticationFailureException("Could not authenticate query", errorContext, null);
        } else if ((code >= 12000 && code < 13000) || (code >= 14000 && code < 15000)) {
            return new IndexFailureException(errorContext);
        } else if (code == 1065) {
            if (message.contains("query_context")) {
                return FeatureNotAvailableException.scopeLevelQuery(ServiceType.QUERY);
            }
            if (message.contains("preserve_expiry")) {
                return FeatureNotAvailableException.queryPreserveExpiry();
            }
        } else if (code == 1080) {
            // engine will proactively send us a timeout and we need to convert it.
            return new UnambiguousTimeoutException("Query timed out while streaming/receiving rows", new CancellationErrorContext(errorContext));
        } else if (code == 1191 || code == 1192 || code == 1193 || code == 1194) {
            return new RateLimitedException(errorContext);
        } else if (code == 3230) {
            String feature = null;
            if (message.contains("Advisor") || message.contains("Advise")) {
                feature = "Query Index Advisor";
            } else if (message.contains("Window")) {
                feature = "Query Window Functions";
            }
            return FeatureNotAvailableException.communityEdition(feature);
        }
    }
    return new CouchbaseException("Unknown query error", errorContext);
}
Also used : IndexExistsException(com.couchbase.client.core.error.IndexExistsException) DocumentNotFoundException(com.couchbase.client.core.error.DocumentNotFoundException) DocumentExistsException(com.couchbase.client.core.error.DocumentExistsException) CasMismatchException(com.couchbase.client.core.error.CasMismatchException) PlanningFailureException(com.couchbase.client.core.error.PlanningFailureException) UnambiguousTimeoutException(com.couchbase.client.core.error.UnambiguousTimeoutException) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) QueryErrorContext(com.couchbase.client.core.error.context.QueryErrorContext) QuotaLimitedException(com.couchbase.client.core.error.QuotaLimitedException) ErrorCodeAndMessage(com.couchbase.client.core.error.ErrorCodeAndMessage) ParsingFailureException(com.couchbase.client.core.error.ParsingFailureException) PreparedStatementFailureException(com.couchbase.client.core.error.PreparedStatementFailureException) IndexNotFoundException(com.couchbase.client.core.error.IndexNotFoundException) DmlFailureException(com.couchbase.client.core.error.DmlFailureException) IndexFailureException(com.couchbase.client.core.error.IndexFailureException) CancellationErrorContext(com.couchbase.client.core.error.context.CancellationErrorContext) RateLimitedException(com.couchbase.client.core.error.RateLimitedException) InternalServerFailureException(com.couchbase.client.core.error.InternalServerFailureException)

Example 5 with CouchbaseException

use of com.couchbase.client.core.error.CouchbaseException in project couchbase-jvm-clients by couchbase.

the class SearchChunkResponseParser method errorsToThrowable.

private CouchbaseException errorsToThrowable(final byte[] bytes) {
    int statusCode = responseHeader().status().code();
    String errorDecoded = bytes == null || bytes.length == 0 ? "" : new String(bytes, CharsetUtil.UTF_8);
    SearchErrorContext errorContext = new SearchErrorContext(HttpProtocol.decodeStatus(responseHeader().status()), requestContext(), statusCode, errorDecoded);
    if (statusCode == 400 && errorDecoded.contains("index not found")) {
        return new IndexNotFoundException(errorContext);
    } else if (statusCode == 500) {
        return new InternalServerFailureException(errorContext);
    } else if (statusCode == 401 || statusCode == 403) {
        return new AuthenticationFailureException("Could not authenticate search query", errorContext, null);
    } else if (statusCode == 400 && errorDecoded.contains("num_fts_indexes")) {
        return new QuotaLimitedException(errorContext);
    } else if (statusCode == 429) {
        if (errorDecoded.contains("num_concurrent_requests") || errorDecoded.contains("num_queries_per_min") || errorDecoded.contains("ingress_mib_per_min") || errorDecoded.contains("egress_mib_per_min")) {
            return new RateLimitedException(errorContext);
        }
    }
    return new CouchbaseException("Unknown search error: " + errorDecoded, errorContext);
}
Also used : CouchbaseException(com.couchbase.client.core.error.CouchbaseException) QuotaLimitedException(com.couchbase.client.core.error.QuotaLimitedException) SearchErrorContext(com.couchbase.client.core.error.context.SearchErrorContext) IndexNotFoundException(com.couchbase.client.core.error.IndexNotFoundException) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) RateLimitedException(com.couchbase.client.core.error.RateLimitedException) InternalServerFailureException(com.couchbase.client.core.error.InternalServerFailureException)

Aggregations

CouchbaseException (com.couchbase.client.core.error.CouchbaseException)46 DocumentNotFoundException (com.couchbase.client.core.error.DocumentNotFoundException)8 Test (org.junit.jupiter.api.Test)8 ByteBuf (com.couchbase.client.core.deps.io.netty.buffer.ByteBuf)7 CasMismatchException (com.couchbase.client.core.error.CasMismatchException)7 RetryExhaustedException (com.couchbase.client.core.retry.reactor.RetryExhaustedException)7 LookupInResult (com.couchbase.client.java.kv.LookupInResult)7 JavaIntegrationTest (com.couchbase.client.java.util.JavaIntegrationTest)7 Duration (java.time.Duration)7 IgnoreWhen (com.couchbase.client.test.IgnoreWhen)6 ArrayList (java.util.ArrayList)6 AuthenticationFailureException (com.couchbase.client.core.error.AuthenticationFailureException)5 RateLimitedException (com.couchbase.client.core.error.RateLimitedException)5 IndexNotFoundException (com.couchbase.client.core.error.IndexNotFoundException)4 UnambiguousTimeoutException (com.couchbase.client.core.error.UnambiguousTimeoutException)4 PathNotFoundException (com.couchbase.client.core.error.subdoc.PathNotFoundException)4 JsonObject (com.couchbase.client.java.json.JsonObject)4 SearchIndex (com.couchbase.client.java.manager.search.SearchIndex)4 List (java.util.List)4 RequestSpan (com.couchbase.client.core.cnc.RequestSpan)3