do Operators instead of a whole Subscriber - java

It's quite appealing to use Action(s) instead of a whole Subscriber when you only need OnNext() merely because it's more readable. But of course, errors happen and if you only use Action1 you'll get an Exception in your app. do operators can be of help here. I'm only concerned these two approaches are fully the same, please confirm or disconfirm. Any pitfalls?
The first approach:
Observable
.just(readFromDatabase())
.doOnError(new Action1<Throwable>() {
#Override public void call(Throwable throwable) {
// handle error
}
}).subscribe(new Action1<SomeData>() {
#Override public void call(SomeData someData) {
// react!
}
});
The second approach:
Observable
.just(readFromDatabase())
.subscribe(new Subscriber<SomeData>() {
#Override public void onCompleted() {
// do nothing
}
#Override public void onError(Throwable e) {
// handle error
}
#Override public void onNext(SomeData someData) {
// react!
}
});
Thank you!

Both approaches aren't quite the same, and you're going to get some surprises out of the first:
First surprise will be that doOnError doesn't consume the error, but only performs some action on it. Consequently, in your case if the stream generates an error, it'll go through your doOnError code, and right after that trigger an OnErrorNotImplementedException, exactly as if the doOnError step wasn't there.
Let's say you realize that, and add an empty error handler to your subscribe call:
Observable
.just(readFromDatabase())
.doOnError(...)
.subscribe(..., error -> { /* already handled */ } );
Then you can meet the next subtle difference. do* blocks are considered part of the stream, which means that any uncatched exception in the block will result in a stream error (as opposed with exceptions thrown in 'onNext/OnError/onComplete' blocks, which get either ignored or immediately thrown, canceling the subscription on their way).
So in the above sample, if we say your database read triggers a stream error A, which gets passed to the doOnError block, which throws an exception B, then the (empty) subscription error handler we added will receive B (and only B).
The later difference isn't very concerning for doOnError (because anyway the stream gets terminated), but can be pretty surprising when occuring in doOnNext, where an exception has a very different behavior than the same exception thrown in subscribe onNext block (error'ed stream versus implicitly canceled stream).

Related

Handling CompletableFuture exceptions in controller

I'm trying to get into CompletableFuture class for a project I'm running, and I got to some question here:
There is the following method: it tries to find a conversation by its ID or hash; and, if not found, it throws an exception. So far, so good.
public ConversationOutput getConversationByIdOrHash(String conversationIdOrHash)
throws ConversationNotFoundException {
Conversation conversation = this.conversationRepository.getByIdOrHash(conversationIdOrHash);
if (conversation == null) {
throw new ConversationNotFoundException(conversationIdOrHash);
}
return this.modelMapper.map(conversation, ConversationOutput.class);
}
Note that I am throwing ConversationNotFoundException from my method signature. My SpringBoot controller is reacting to this exception and it's all working fine since the beginning.
What I'm trying to do is to make this to a CompletableFuture return and actually throwing an exception, something similar to:
public CompletableFuture<ConversationOutput> getConversationByIdOrHashAsync(String conversationIdOrHash)
throws ConversationNotFoundException {
return CompletableFuture.supplyAsync(() -> this.getConversationByIdOrHash(conversationIdOrHash));
}
I've seen posts where people use exceptionally to handle exceptions, but what I really want to do is to throw it to my controller and let it handle it. Any suggestions of how can I make it?
Thank you all!
The question is do you care about the result of CompletableFuture.
CompletableFuture is like a special task and it is processed on other thread. If you don't invoke .join() you won't receive the results of CompletableFuture. This method also will propagate the exception if any occured. However it waits for CompletableFuture to finish and blocks the request.
However, there is no way to get exceptions from the inside of the CompletableFuture without waiting, you have to treat it like other task.
You can pass the completed future in case of a success, and failed future along with your custom exception.
public CompletableFuture<ConversationOutput> getConversationByIdOrHashAsync(String conversationIdOrHash) {
try {
return CompletableFuture.completedFuture(this.getConversationByIdOrHash(conversationIdOrHash));
} catch (ConversationNotFoundException e) {
return CompletableFuture.failedFuture(e);
}
}
and then at your controller level you can handle the exception.
final CompletableFuture<ConversationOutput> future = getConversationByIdOrHashAsync("idOrHash");
future.whenComplete((r, e) -> {
if (e != null) {
if (e instanceof ConversationNotFoundException) {
//handling
}
}
});

Throwing Exception in a nested Flowable's onNext is causing an UndeliverableException

I've code like this in a repository:
return Completable.fromAction {
// Some code
loginService.login(id)
.subscribe(
{ response ->
if(response.isNotSuccessful()) {
throw Exception()
}
// Some code
},
{ e ->
throw e
}
)
}
I've code like this in a ViewModel:
fun onLoginAction(id) {
repository.login(id)
.subscribe(
{
showSuccess()
},
{
showFailure()
}
)
}
Basically, the ViewModel calls the login method in the repository which returns the Completable.
This results in an UndeliverableException when the response is not successful. I want the Completable's subscriber's onError() method to be called. How do I do this?
I don't have enough knowledge to actually say this with certainty, but I still think this has some value to you and it's too big for a comment.
Here's what I think it's happening. When onError fails rx won't run this through the same observable stream. Instead, it will propagate this to the RxPlugins error handler and eventually to the default exception handler in your system. You can find this here.
This is to say that when loginService.login(id) throws the exception in the onError, the Completable stream won't have a chance to catch it and forward it to the onError of the outer subscribe. In other words, the completable stream is independent of the login service one.
Usually, you'd want to create one single stream and let the view model subscribe to it. If you have more than one stream, rx has loads of operators to help you chain these. Try and make the repository return one stream from the service. Something like this:
fun login(id) = loginService.login(id)
And now on the view model, you can check if the call was or not successful using the same method - response.isNotSuccessful()

Any design patterns for handling the following case in Java?

I'm new to Java & its design patterns, I have a scenario like this:
Method 1 calls Method 2.
Method 2 looks like the following:
public String createUser(String username, String password) {
someApi.do(config -> {
//code here with respect to someApi.
});
}
now the trick is I need to return the value to caller which is method 1. If there are no exceptions then that is fine. However the code block inside do can throw exception, which will be handled in a separate listener class like this:
public class TestListener implements SomeApiListener {
#Override
public void exception(Throwable cause) {
}
}
Now how should I send back the exception to method 1 from this listener? I'm really confused.
it's not clear what that API do, where the listener is assigned, and what other methods it has, like if there is also onSuccess() ?
what i got from this, is that, you are dealing with async call, which usually do not return a value directly, it deals with a CallBack which in your case is SomeApiListener
So, ... I would make createUser() receives extra arg, SomeApiListener, pass the listener as anonymous inner class (with implementation) when calling the method (from caller).
ex,
public String createUser(String username, String password, SomeApiListener listener) {
someApi.do(config -> {
//code here with respect to someApi.
//somewhere here you are creating a TestListener ?,
//well... don't, and use the one passed from caller (listener)
});
}
Caller part will look like this:
public void method1(){
//..some code ...
createUser(username, password, new SomeApiListener(){
#Override
public void exception(Throwable cause) {
//handle exception...
}
#Override
public void success(Response response) {
//handle response ...
}
});
}
Note: you can still pass TetstListern, if you want, in that case you will have to have a physical class (local class) defined and instantiated, the anonymous-inner-class is somehow a shortcut for that, you don't create a local class, just pass it as an arg.
You can't, at least not in any simple way. I'd expect the documentation for your someApi to demonstrate some common use cases, with exception handling included. If you're combining different ways of programming ("normal" java & functional programming), you can get into tricky situations.
Based on the information you've given, a clumsy solution could look something like this (code obviously not fit for compilation):
public class MyClass implements SomeApiListener {
private Throwable e;
public void exception(Throwable cause) {
e = cause;
}
public void method1() {
createUser("foo", "bar");
if(e != null) {
// Exception was thrown, do something with it
}
}
}
However this is in no way a recommendation. It's clumsy, hacky and bad in every way. A better solution would involve not trying to send the exception back to method1, but instead to modify your code to work in the way that someApi expects.
It depends on your design on how to handle exceptions. Normally, if the method 2 is an utility method then throw the exception back to method 1 and let it handle the exception. Else, if method 2 understands the use case for which it is called then handle the exception there. There are no hard and fast rules, but keep the utility classes clean and send the exception back to the caller so that caller can handle it.

Jersey/JAX-RS 2 AsyncResponse - how to keep track of current long-polling callers

My goal is to support long-polling for multiple web service callers, and to keep track of which callers are currently "parked" on a long poll (i.e., connected). By "long polling," I mean that a caller calls a web service and the server (the web service) does not return immediately, but keeps the caller waiting for some preset period of time (an hour in my application), or returns sooner if the server has a message to send to the caller (in which case the server returns the message by calling asyncResponse.resume("MESSAGE")).
I'll break this into two questions.
First question: is this a reasonable way to "park" the callers who are long-polling?
#GET
#Produces(MediaType.TEXT_PLAIN)
#ManagedAsync
#Path("/poll/{id}")
public Response poller(#Suspended final AsyncResponse asyncResponse, #PathParam("id") String callerId) {
// add this asyncResponse to a HashMap that is persisted across web service calls by Jersey.
// other application components that may have a message to send to a caller will look up the
// caller by callerId in this HashMap and call resume() on its asyncResponse.
callerIdAsyncResponseHashMap.put(callerId, asyncResponse);
asyncResponse.setTimeout(3600, TimeUnit.SECONDS);
asyncResponse.setTimeoutHandler(new TimeoutHandler() {
#Override
public void handleTimeout(AsyncResponse asyncResponse) {
asyncResponse.resume(Response.ok("TIMEOUT").build());
}
});
return Response.ok("COMPLETE").build();
}
This works fine. I'm just not sure if it's following best practices. It seems odd to have the "return Response..." line at the end of the method. This line is executed when the caller first connects, but, as I understand it, the "COMPLETE" result is never actually returned to the caller. The caller either gets "TIMEOUT" response or some other response message sent by the server via asyncResponse.resume(), when the server needs to notify the caller of an event.
Second question: my current challenge is to accurately reflect the population of currently-polling callers in the HashMap. When a caller stops polling, I need to remove its entry from the HashMap. A caller can leave for three reasons: 1) the 3600 seconds elapse and so it times out, 2) another application component looks up the caller in the HashMap and calls asyncResponse.resume("MESSAGE"), and 3) the HTTP connection is broken for some reason, such as somebody turning off the computer running the client application.
So, JAX-RS has two callbacks I can register to be notified of connections ending: CompletionCallback (for my end-poll reasons #1 and #2 above), and ConnectionCallback (for my end-poll reason #3 above).
I can add these to my web service method like this:
#GET
#Produces(MediaType.TEXT_PLAIN)
#ManagedAsync
#Path("/poll/{id}")
public Response poller(#Suspended final AsyncResponse asyncResponse, #PathParam("id") String callerId) {
asyncResponse.register(new CompletionCallback() {
#Override
public void onComplete(Throwable throwable) {
//?
}
});
asyncResponse.register(new ConnectionCallback() {
#Override
public void onDisconnect(AsyncResponse disconnected) {
//?
}
});
// add this asyncResponse to a HashMap that is persisted across web service calls by Jersey.
// other application components that may have a message to send to a caller will look up the
// caller by callerId in this HashMap and call resume() on its asyncResponse.
callerIdAsyncResponseHashMap.put(callerId, asyncResponse);
asyncResponse.setTimeout(3600, TimeUnit.SECONDS);
asyncResponse.setTimeoutHandler(new TimeoutHandler() {
#Override
public void handleTimeout(AsyncResponse asyncResponse) {
asyncResponse.resume(Response.ok("TIMEOUT").build());
}
});
return Response.ok("COMPLETE").build();
}
The challenge, as I said, is to use these two callbacks to remove no-longer-polling callers from the HashMap. The ConnectionCallback is actually the easier of the two. Since it receives an asyncResponse instance as a parameter, I can use that to remove the corresponding entry from the HashMap, like this:
asyncResponse.register(new ConnectionCallback() {
#Override
public void onDisconnect(AsyncResponse disconnected) {
Iterator<Map.Entry<String, AsyncResponse>> iterator = callerIdAsyncResponseHashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, AsyncResponse> entry = iterator.next();
if (entry.getValue().equals(disconnected)) {
iterator.remove();
break;
}
}
}
});
For the CompletionCallback, though, since the asyncResponse is already done or cancelled at the time the callback is triggered, no asyncResponse parameter is passed in. As a result, it seems the only solution is to run through the HashMap entries checking for done/cancelled ones and removing them, like the following. (Note that I don't need to know whether a caller left because resume() was called or because it timed out, so I don't look at the "throwable" parameter).
asyncResponse.register(new CompletionCallback() {
#Override
public void onComplete(Throwable throwable) {
Iterator<Map.Entry<String, AsyncResponse>> iterator = callerIdAsyncResponseHashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, AsyncResponse> entry = iterator.next();
if (entry.getValue().isDone() || entry.getValue().isCancelled()) {
iterator.remove();
}
}
}
});
Any feedback would be appreciated. Does this approach seem reasonable? Is there a better or more Jersey/JAX-RS way to do it?
Your poller() method does not need to return a Response in order to participate in asynchronous processing. It can return void. If you are doing anything complex in the poller however you should consider wrapping the whole method in a try/catch block that resumes your AsyncResponse object with the exception to ensure that any RuntimeExceptions or other unchecked Throwables are not lost. Logging these exceptions in the catch block here also seems like a good idea.
I'm currently researching the question of how to reliably catch an asynchronous request being cancelled by the client and have read at one question that suggests the mechanism isn't working for the questioner[1]. I'll leave it to others to fill out this information for the moment.
[1] AsyncResponse ConnectionCallback does not fire in Jersey

Handling an exception as a method argument

I am looking for a design pattern to handle Exception instances received as method arguments.
To put some context into the question, I am using GWT and have various asynchronous handlers that usually come in a form similar to:
public interface AsyncCallback<T> {
void onFailure(Throwable caught);
void onSuccess(T result);
}
So, the onFailure method receives a Throwable instance that I need to handle.
Now, I have a number of exceptions I can receive in this method, for example
ConstraintViolationException
TimeoutException
NoSuchElementException
In my handling code I could of course write the following:
void handleException(final Exception e) {
if(e instanceof TimeoutException) {
handleTimeout();
} else if (e instanceof NoSuchElementException) {
handleInvalidElement();
} else {
stopAndCatchFire();
}
}
But to my eye, that looks very ugly. The large if..else if chain combined with heavy usage of instanceof seems like something that should be avoided.
I thought that maybe I could use the try...catch construct to handle the Exception using something like the following:
void handleException(final Exception e) {
try {
throw e;
} catch (TimeoutException te) {
handleTimeout();
} catch (NoSuchElementException nsee) {
handleInvalidElement();
} catch (Exception ex) {
stopAndCatchFire();
}
}
But this seems like an abuse somehow. Do you see any downsides to the second approach or another approach I could go with to avoid the first case?
Could you not have a dictionary of exceptionHandlers keyed by the type of exception they handle, then when you get a exception you look in the dictionary for the handler for the exception type. If there is one, then pass the exception to the handler, if there isn't then use the default handler.
So your handler becomes something like this:
void handleException(final Exception e) {
if (handlers.containsKey(e.getType())
{
handlers[e.getType()].handle(e);
}
else
{
defaultHandler.handle(e);
}
}
My Java is a bit rusty, so the example is c-sharpy but should be simple enough to translate (though I remembered not to capitalise the first letter of everything :))
This approach should have the advantage that you can add new handlers simply.
It will however suffer if you have the same handler for sub types, as you will have to register each subtype explicitly.
To get around this issue simply make each handler responsible for making the decision about whether it can handle an exception:
public interface ExceptionHandler
{
bool canHandle(Exception e);
void handle(Exception e)
}
then just put the handlers in a list an iterate asking each one if it can handle the current exception and when you find one that can, get it to handle it.
But to my eye, that looks very ugly. The large if..else if chain combined with heavy usage of instanceof seems like something that should be avoided.
I don't agree. I think this snippet of code is using both language constructs exactly how they were intended. If the code becomes unmanageable (too many clauses) then you should question the approach to error handling generally, rather than the specifics of this method. At that stage you might want to consider AOP.
The second approach on the other hand is horrible ;)
You can make it more elegant just by handling the if statements inside the exceptions inside the function.
void handleException(Exception e){
handleOne(e)
handleTwo(e)
...
}
It looks prettier. Of course, every function is always called, but its first line is just an if statement. There are variations - e.g. make your handle functions guava function objects, put them in a list, and iterate through them until you get the first one that returns "true". Something like:
public class handlerOne implements Function<Exception, Boolean> {
Boolean apply(Exception input) {
return handlerOne();
}
}
Then your handle function can be something like:
void handleException(Exception e){
list<Function<Exception, Boolean> list = Object.getHandlers(); //store your handlers somewhere
for(Function<Exception, Boolean> f : list){
if(f.apply(e)){
break
}
}
}
That way you insure only one handler which works is called, and you can control the order by changing the order of the list, since the list iterator will return them in order.
Control flow on exceptions should be avoided, and should certainly not be in the onFailure. the onFailure method should be as simple as possible.
Modify whatever code is run asynchronously to handle the exception cases there. The ElementNotFound-exception could be handled by just checking if an element exists prior to doing anything. Timeout-exception could be handled by surrounding the code that can timeout (calling a webservice or something)?) by a try .. catch block.
Then extend the result-type T to contain extra information that a timeout occurred or an element is not found - if needed.

Categories