All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.vrap.rmf.base.client.http.ErrorMiddlewareImpl Maven / Gradle / Ivy

There is a newer version: 17.17.0
Show newest version

package io.vrap.rmf.base.client.http;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.function.Function;

import io.vrap.rmf.base.client.*;
import io.vrap.rmf.base.client.error.HttpExceptionFactory;

/**
 * Default implementation of an {@link ErrorMiddleware} to create exceptions based on the HTTP status code
 */
class ErrorMiddlewareImpl implements ErrorMiddleware {
    private final HttpExceptionFactory exceptionFactory;
    private final ExceptionMode exceptionMode;

    @Deprecated
    public ErrorMiddlewareImpl(final ResponseSerializer serializer) {
        this(HttpExceptionFactory.of(serializer));
    }

    public ErrorMiddlewareImpl(HttpExceptionFactory exceptionFactory) {
        this(exceptionFactory, ExceptionMode.COMPLETION_EXCEPTION);
    }

    public ErrorMiddlewareImpl(HttpExceptionFactory exceptionFactory, ExceptionMode mode) {
        this.exceptionFactory = exceptionFactory;
        this.exceptionMode = mode;
    }

    @Override
    public CompletableFuture> invoke(final ApiHttpRequest request,
            final Function>> next) {
        if (exceptionMode == ExceptionMode.COMPLETION_EXCEPTION) {
            return next.apply(request).thenApply(response -> {
                if (response.getStatusCode() >= 400) {
                    throw exceptionFactory.create(request, response);
                }
                return response;
            });
        }

        CompletableFuture> result = new CompletableFuture<>();
        next.apply(request).whenComplete((response, throwable) -> {
            if (throwable != null) {
                Throwable unwrap = throwable instanceof CompletionException ? throwable.getCause() : throwable;
                result.completeExceptionally(unwrap);
            }
            if (response != null) {
                if (response.getStatusCode() >= 400) {
                    try {
                        result.completeExceptionally(exceptionFactory.create(request, response));
                    }
                    catch (Throwable e) {
                        result.completeExceptionally(e);
                    }
                }
            }
            result.complete(response);
        });

        return result;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy