user1120821
user1120821

Reputation: 449

Vertx eventbus rx exceptionhandling

When using Vertx eventbus with a request-reply pattern, I end up with duplicate exception handling that I would like to avoid. I have the following code:

void handle(Message<JsonObject> message) {
    try {
        // do stuff
        message.reply(..);
    } catch (Exception e) {
        message.fail(..);  // in any case reply with fail msg
    }
 }

But now suppose we use some javarx service like this:

void handle(Message<JsonObject> message) {
    try {
        // do some stuff..
        service.foo()
            .subscribe(x -> {
                message.reply(..);
            }, t -> {
                message.fail(..); // how to avoid this duplication??
            });
    } catch (Exception e) {
        message.fail(..);  // in any case reply with fail msg
    }
 }

I have to catch a general exception plus I have to subscribe for onError. In both cases I simply want to reply with the same general fail message. How to avoid this duplication?

Upvotes: 1

Views: 259

Answers (1)

user1120821
user1120821

Reputation: 449

Answering my own question since I came up with a solution by wrapping all code in a Rx structure like this:

void handle(Message<JsonObject> message) {
    // do some stuff..
    Single.just(message)
        .flatMap(m -> {
           // so some stuff..
           return service.foo();
         })
        .subscribe(x -> {
            message.reply(..);
        }, t -> {
            message.fail(..); // we get here even if 'do some stuff' part throws runtimeexception
        });
 }

Upvotes: 1

Related Questions