Search code examples
javarx-java2vert.x

Convert function into a completable with custom Exceptions


I have a vertx service for all message-broker related operations. For e.g. an exchange creation function looks like this

@Override
    public BrokerService createExchange(String exchange, 
    Handler<AsyncResult<JsonArray>> resultHandler) {
        try {
            getAdminChannel(exchange).exchangeDeclare(exchange, "topic", true);
            resultHandler.handle(Future.succeededFuture());
        } catch(Exception e) {
            e.printStackTrace();
            resultHandler.handle(Future.failedFuture(e.getCause()));
        }
        return this;
    }

I am in the process of converting my entire codebase into rxjava and I would like to convert functions like these into completables. Something like:

try {
    getAdminChannel(exchange).exchangeDeclare(exchange, "topic", true);
    Completable.complete();
} catch(Exception e) {
    Completable.error(new BrokerErrorThrowable("Exchange creation failed"));
}

Furthermore, I would also like to be able to throw custom errors like Completable.error(new BrokerErrorThrowable("Exchange creation failed")) when things go wrong. This is so that I'll be able to catch these errors and respond with appropriate HTTP responses.

I saw that Completable.fromCallable() is one way to do it, but I haven't found a way to throw these custom exceptions. How do I go about this? Thanks in advance!


Solution

  • I was able to figure it out. All I had to do was this:

    @Override
      public BrokerService createExchange(String exchange, Handler<AsyncResult<Void>> resultHandler) {
        Completable.fromCallable(
                () -> {
                  try {
                    getAdminChannel(exchange).exchangeDeclare(exchange, "topic", true);
                    return Completable.complete();
                  } catch (Exception e) {
                    return Completable.error(new InternalErrorThrowable("Create exchange failed"));
                  }
                })
            .subscribe(CompletableHelper.toObserver(resultHandler));
    
        return this;
      }