@Async с CompletableFuture # get not выбрасывает пользовательское исключение RuntimeException - PullRequest
0 голосов
/ 23 октября 2018

У меня есть этот метод:

@Async
@Override
public CompletableFuture<List<ProductDTO>> dashboard( ) throws GeneralException {

    List<Product> products = newArrayList();

    /*....
    ....*/

    //I want this exception when calling CompletableFuture#get()
    if ( products.isEmpty() ) {
        throw new GeneralException( "user.not-has.product-message",
                "user.not-has.product-title" );
    }

    return CompletableFuture
            .completedFuture( ...) );
}

И GeneralException определяется следующим образом:

public class GeneralException extends RuntimeException {...}

Проблема в том, когда GeneralException выбрасывается, когда я вызываюCompletableFuture#get() чтобы получить мои данные или исключение, у меня есть java.util.concurrent.ExecutionException, а не мой пользовательский GeneralException.Spring Doc заявляет следующее:

Когда метод @Async имеет возвращаемое значение Future, легко управлять исключением, которое было сгенерировано во время выполнения метода, так как это исключение выдаетсяпри вызове get по результату Future.

Что я делаю не так?Большое спасибо

РЕДАКТИРОВАТЬ: Это код клиента:

public static <T> T retrieveDataFromCompletableFuture( @NotNull CompletableFuture<T> futureData ) {
    T data = null;
    try {
        data = futureData.get();
    } catch ( Exception e ) {
        log.error( "Can't get data ", e );
    }
    return data;
}

И исключение:

java.util.concurrent.ExecutionException: org.app.exceptions.GeneralException: user.not-has.product-message
at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895)
.....
Caused by: org.app.exceptions.GeneralException: user.not-has.product-message

Почему у меня все еще естьjava.util.concurrent.ExecutionException

1 Ответ

0 голосов
/ 23 октября 2018

Старайтесь не выбрасывать исключение, а завершайте функцию с исключением

@Async
@Override
public CompletableFuture<List<ProductDTO>> dashboard( ) throws GeneralException {

    List<Product> products = newArrayList();

    /*....
    ....*/

    //I want this exception when calling CompletableFuture#get()
    if ( products.isEmpty() ) {
        CompletableFuture<List<ProductDTO>> result = new CompletableFeature<>();
        result.completeExceptionally(new GeneralException("user.not-has.product-message", 
            "user.not-has.product-title"
        );
        return result;
    }

    return CompletableFuture
        .completedFuture( ...) );
}
...