Search in sources :

Example 6 with RemoteException

use of com.palantir.conjure.java.api.errors.RemoteException in project conjure-java-runtime by palantir.

the class RemoteExceptionResponseHandlerTest method testEncodingAndDecodingWebException.

private static void testEncodingAndDecodingWebException(Class<? extends WebApplicationException> exceptionClass, Response.Status status) {
    WebApplicationException exceptionToProcess;
    try {
        exceptionToProcess = exceptionClass.getConstructor(String.class, Response.Status.class).newInstance(message, status);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        throw new RuntimeException(e);
    }
    RemoteException exception = encodeAndDecode(exceptionToProcess).get();
    assertThat(exception.getCause()).isNull();
    assertThat(exception.getStatus()).isEqualTo(status.getStatusCode());
    assertThat(exception.getError().errorCode()).isEqualTo(exceptionClass.getName());
    assertThat(exception.getMessage()).startsWith("RemoteException: " + exceptionClass.getName() + " (" + message + ")");
}
Also used : Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException) RemoteException(com.palantir.conjure.java.api.errors.RemoteException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 7 with RemoteException

use of com.palantir.conjure.java.api.errors.RemoteException in project conjure-java-runtime by palantir.

the class RemoteExceptionResponseHandlerTest method handlesNotAuthorizedException.

@Test
public void handlesNotAuthorizedException() throws Exception {
    NotAuthorizedException originalException = new NotAuthorizedException(message, Response.Status.UNAUTHORIZED);
    RemoteException exception = encodeAndDecode(originalException).get();
    assertThat(exception.getCause()).isNull();
    assertThat(exception.getStatus()).isEqualTo(Response.Status.UNAUTHORIZED.getStatusCode());
    assertThat(exception.getError().errorCode()).isEqualTo(NotAuthorizedException.class.getName());
    assertThat(exception.getError().errorName()).isEqualTo(message);
    assertThat(exception.getMessage()).isEqualTo("RemoteException: javax.ws.rs.NotAuthorizedException (" + message + ") with instance ID " + exception.getError().errorInstanceId());
}
Also used : NotAuthorizedException(javax.ws.rs.NotAuthorizedException) RemoteException(com.palantir.conjure.java.api.errors.RemoteException) Test(org.junit.Test)

Example 8 with RemoteException

use of com.palantir.conjure.java.api.errors.RemoteException in project conjure-java-runtime by palantir.

the class RemoteExceptionResponseHandlerTest method testSpecificException.

@Test
public void testSpecificException() {
    RemoteException exception = encodeAndDecode(new IllegalArgumentException("msg")).get();
    assertThat(exception).isInstanceOf(RemoteException.class);
    assertThat(exception.getMessage()).startsWith("RemoteException: java.lang.IllegalArgumentException (msg)");
}
Also used : RemoteException(com.palantir.conjure.java.api.errors.RemoteException) Test(org.junit.Test)

Example 9 with RemoteException

use of com.palantir.conjure.java.api.errors.RemoteException in project conjure-java-runtime by palantir.

the class RemotingOkHttpCall method enqueueInternal.

private void enqueueInternal(Callback callback) {
    super.enqueue(new LeakedResponseClosingCallback(new Callback() {

        @Override
        public void onFailure(Call call, IOException exception) {
            if (isCanceled()) {
                callback.onFailure(call, exception);
                return;
            }
            urls.markAsFailed(request().url());
            // Fail call if backoffs are exhausted or if no retry URL can be determined.
            Optional<Duration> backoff = backoffStrategy.nextBackoff();
            if (!shouldRetry(exception, backoff)) {
                callback.onFailure(call, new SafeIoException("Failed to complete the request due to an IOException", exception, UnsafeArg.of("requestUrl", call.request().url().toString())));
                return;
            }
            Optional<HttpUrl> redirectTo = urls.redirectToNext(request().url());
            if (!redirectTo.isPresent()) {
                callback.onFailure(call, new SafeIoException("Failed to determine valid failover URL", exception, UnsafeArg.of("requestUrl", call.request().url().toString()), UnsafeArg.of("baseUrls", urls.getBaseUrls())));
                return;
            }
            retryIfAllowed(callback, call, exception, () -> {
                if (log.isInfoEnabled()) {
                    log.info("Retrying call after failure", SafeArg.of("backoffMillis", backoff.get().toMillis()), // format this value asynchronously.
                    SafeArg.of("backoffState", backoffStrategy.toString()), UnsafeArg.of("requestUrl", call.request().url().toString()), UnsafeArg.of("redirectToUrl", redirectTo.get().toString()), exception);
                }
                Tags.AttemptSpan nextAttempt = createNextAttempt();
                Request redirectedRequest = request().newBuilder().url(redirectTo.get()).tag(Tags.AttemptSpan.class, nextAttempt).build();
                RemotingOkHttpCall retryCall = client.newCallWithMutableState(redirectedRequest, backoffStrategy, maxNumRelocations - 1, Optional.of(call));
                scheduleExecution(backoff.get(), nextAttempt, retryCall, callback);
            });
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            urls.markAsSucceeded(request().url());
            // Relay successful responses
            if (response.code() / 100 <= 2) {
                callback.onResponse(call, response);
                return;
            }
            ResponseBody maybeResponseBody = response.body();
            // Buffer the response into a byte[] so that multiple handler can safely consume the body.
            // This consumes and closes the original response body.
            Supplier<Response> errorResponseSupplier;
            try {
                byte[] body = maybeResponseBody == null ? null : maybeResponseBody.bytes();
                // so error handlers can read the body without breaking subsequent handlers
                errorResponseSupplier = () -> buildFrom(response, body);
            } catch (IOException e) {
                onFailure(call, e);
                return;
            } finally {
                close(response);
            }
            // Handle to handle QoS situations: retry, failover, etc.
            Optional<QosException> qosError = qosHandler.handle(errorResponseSupplier.get());
            if (qosError.isPresent()) {
                qosError.get().accept(createQosVisitor(callback, call, errorResponseSupplier.get()));
                return;
            }
            // Handle responses that correspond to RemoteExceptions / SerializableErrors
            Optional<RemoteException> httpError = remoteExceptionHandler.handle(errorResponseSupplier.get());
            if (httpError.isPresent()) {
                callback.onFailure(call, new IoRemoteException(httpError.get()));
                return;
            }
            // Catch-all: handle all other responses
            Optional<UnknownRemoteException> unknownHttpError = unknownRemoteExceptionHandler.handle(errorResponseSupplier.get());
            if (unknownHttpError.isPresent()) {
                callback.onFailure(call, new IoUnknownRemoteException(unknownHttpError.get()));
                return;
            }
            callback.onFailure(call, new SafeIoException("Failed to handle request, this is an conjure-java-runtime bug."));
        }
    }));
}
Also used : QosException(com.palantir.conjure.java.api.errors.QosException) UnknownRemoteException(com.palantir.conjure.java.api.errors.UnknownRemoteException) SafeIoException(com.palantir.logsafe.exceptions.SafeIoException) Call(okhttp3.Call) Request(okhttp3.Request) Duration(java.time.Duration) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) Callback(okhttp3.Callback) FutureCallback(com.google.common.util.concurrent.FutureCallback) RemoteException(com.palantir.conjure.java.api.errors.RemoteException) UnknownRemoteException(com.palantir.conjure.java.api.errors.UnknownRemoteException)

Example 10 with RemoteException

use of com.palantir.conjure.java.api.errors.RemoteException in project conjure-java-runtime by palantir.

the class Retrofit2ClientApiTest method makeFutureRequestError.

private void makeFutureRequestError(Supplier<Future<String>> futureSupplier) throws JsonProcessingException {
    SerializableError error = SerializableError.builder().errorCode("errorCode").errorName("errorName").build();
    server.enqueue(new MockResponse().setResponseCode(500).setHeader(HttpHeaders.CONTENT_TYPE, "application/json").setBody(ObjectMappers.newClientJsonMapper().writeValueAsString(error)));
    assertThatThrownBy(() -> Futures.getUnchecked(futureSupplier.get())).isInstanceOf(UncheckedExecutionException.class).hasCauseInstanceOf(RemoteException.class).satisfies(e -> assertThat(((RemoteException) e.getCause()).getError()).isEqualTo(error));
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) SerializableError(com.palantir.conjure.java.api.errors.SerializableError) RemoteException(com.palantir.conjure.java.api.errors.RemoteException)

Aggregations

RemoteException (com.palantir.conjure.java.api.errors.RemoteException)22 Test (org.junit.jupiter.api.Test)11 SerializableError (com.palantir.conjure.java.api.errors.SerializableError)7 ServiceException (com.palantir.conjure.java.api.errors.ServiceException)7 Test (org.junit.Test)6 UnknownRemoteException (com.palantir.conjure.java.api.errors.UnknownRemoteException)5 Response (okhttp3.Response)5 TypeMarker (com.palantir.conjure.java.undertow.lib.TypeMarker)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 Method (java.lang.reflect.Method)3 Type (java.lang.reflect.Type)3 FutureCallback (com.google.common.util.concurrent.FutureCallback)2 BodySerDe (com.palantir.dialogue.BodySerDe)2 TestResponse (com.palantir.dialogue.TestResponse)2 SafeIoException (com.palantir.logsafe.exceptions.SafeIoException)2 IOException (java.io.IOException)2 InterruptedIOException (java.io.InterruptedIOException)2 Call (okhttp3.Call)2 Callback (okhttp3.Callback)2 MockResponse (okhttp3.mockwebserver.MockResponse)2