When a called the persist() method from server, a exception is throwed after a validation in uniques of a email.
The problem is that onSuccess method from client is called, instead of onFailure. Here is the code.
RequestContext req = driver.flush();
if (req.isChanged() && !driver.hasErrors()) {
saveButton.setEnabled(false);
req.fire(new Receiver<Void>() {
#Override
public void onSuccess(Void response) {
//anything
}
#Override
public void onFailure(ServerFailure error) {
//anything
}
});
}
public User persist() throws GenericException{ // extends from Exception
//query in database
throw new GenericException("Email must be unique");
//save case is correct
}
Any help?
Why do you think that throwing exception == calling onFailure method? Did you analyzed code - is somewhere exception handler that catches your exceptions and converts them to onFaliure calls?
Related
I am using HttpAsyncClient in order to GET some urls. In some cases, let's say when I receive status HTTP-304, I would like to abandon the ongoing call. I don't want to wait for body, I don't want to spend the machine resources on it. Is there any way of cancelling this? Apparently things like futureResponse.cancel(true) or futureResponse.finalize() do not work.
Future<Response> futureResponse = httpClient.prepareGet("some-url").addHeader("some", "header").execute(new AsyncCompletionHandler<Response>() {
#Override
public State onStatusReceived(HttpResponseStatus status) throws Exception {
logger.info("status {}", status);
// CONDITIONAL FINISH THIS CALL
return super.onStatusReceived(status);
}
#Override
public Response onCompleted(Response response) throws Exception {
logger.info("its ok");
return response;
}
#Override
public void onThrowable(Throwable t) {
logger.error(t);
}
});
From the doc:
You can return ABORT to close the connection.
#Override
public State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
Integer status = responseStatus.getStatusCode();
if (304 == status) { // CONDITIONAL FINISH THIS CALL
return State.ABORT;
} else {
doSomething()
return ...
}
}
We have been using netty-handler 4.0.28.Final. We have a test where we write invalid xml to a test channel. As below ctx.close() would be called and channelInactive would fire.
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable exc) {
if (connectionListener == null) {
return;
}
// Treat unexpected exceptions as fatal to the connection
try {
connectionListener.connectionError(exc);
} finally {
ctx.close();
}
}
#Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (connectionListener == null) {
return;
}
connectionListener.connectionClosed();
}
I have been tasked with updating netty to netty-all 4.1.11.Final. Since updating, channelInactive is not getting called. (Only gets called when when we call finish() on the EmbeddedChannel during tidy up).
Why would channelInactive no longer be called when we call ctx.close()?
This is a bug and will be fixed in the next release.
see https://github.com/netty/netty/pull/6897
OkHttp library Callback interface is declared as
public interface Callback {
void onFailure(Request request, IOException e);
void onResponse(Response response) throws IOException;
}
Unhandled exceptions from onResponse method will get eaten up by Call class as I have recently discovered in Callback failure for cancelled call in OkHttp
I have few questions related to that design.
First, wouldn't it be better have different declaration of onResponse method in order to force catching exceptions in onResponse rather than throwing them, since they will be eaten up.
Is this design flaw in OkHttp Callback interface or is this kind of code common practice in Java?
Second, when http request reaches onResponse callback method I would expect that canceling request at that point should be prohibited. I would say this is a bug. Am I right?
I'm also struggling with this, for now I've solved it as follows:
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// AlertDialog, etc.
}
});
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
onFailure(call, new IOException("Unexpected code: " + response));
}
// else success
}
});
The key point is calling OnFailure inside OnResponse. I wasn't able to access the Exception in any other way (though there probably are other ways; this gives OnFailure some additional usefulness in my opinion, and it conveys intent fairly well I think). Note that OnFailure can be called for other reasons: https://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/Callback.html
What is the requirement in a Service implementation so that the ErrorCallback will be able to print the error message on the UI like.
I tried injecting a ErrorCallback in the Service call code, and when I print the Message object its null.
What should be the Service implementation look like, should I put throws SomeException on the implementation method? Or?
myService.call(new RemoteCallback<String>() {
#Override
public void callback(String response) {
Multimap<String, String> state = ArrayListMultimap.create();
state.put("hash", response);
submit.go(state);
}
}, new ErrorCallback() {
#Override
public boolean error(Message message, Throwable throwable) {
throwable.printStackTrace();
Window.alert("Error: " + message);
return false;
}
}).createmy(my);
Your code should work as stated in the question. The exception thrown by the remote service should be delivered to you in the throwable parameter to your ErrorCallback.error() method.
You only need to put a throws clause on the remote interface if you want to throw a checked exception. Unchecked exceptions should work as you've done it. In fact, there is a disadvantage to declaring checked exceptions on remote interfaces: you will have to surround your RPC calls with a useless try/catch block, like this:
#Remote public interface MyService {
Result dangerousOperation() throws MyCheckedException;
}
and the calling code:
try {
myService.call(new RemoteCallback<Result>() {
#Override
public void callback(final Result result) {
Window.alert("Yay, got a result: " + result);
}
},
new BusErrorCallback() {
#Override
public boolean error(Message message, Throwable throwable) {
Window.alert("Got an exception from the remote service: " + throwable);
return false;
}
}).dangerousOperation();
}
catch (MyCheckedException e) {
throw new AssertionError(); // can't happen: caller stub won't throw this
}
So you're probably better off with the unchecked exception.
It is possible to throw exception inside onFailure() method of GWT's RPC call? Because this method will be called later, after server response, I apologize that here may happen something bad..
For example:
public void method() {
try {
rpc.invoke(new AsyncCallback<Void>() {
#Override
public void onSuccess(Void arg0) {}
#Override
public void onFailure(Throwable arg0) {
throw new RuntimeException("Error message"); //HERE
}
});
}
catch (Exception e) {
Window.alert(e.getMessage()); // AND CATCH ABOVE EXCEPTION HERE
}
}
I usually use the following approach on my GWT projects:
1) Create an MyExceptionsHandler:
#Singleton
public class MyExceptionsHandler implements
GWT.UncaughtExceptionHandler,
RpcFailureEvent.Handler, // create corresponding GwtEvent-s
AnyOtherErrorEvent.Handler {
public MyExceptionsHandler(EventBus evenBus) {
eventBus.addHandler(RpcFailureEvent.TYPE, this);
eventBus.addHandler(AnyOtherErrorEvent.TYPE, this);
}
// implement corresponding methods for interfaces
}
2) On entry point:
GWT.setUnchaughtExceptionHandler(myExceptionHandler);
3) In any other place you have an error, which you don't know how to handle:
rpc.invoke(new AsyncCallback<Void>() {
#Override
public void onSuccess(Void arg0) {}
#Override
public void onFailure(Throwable arg0) {
eventBus.fireEvent(new RpcFailureEvent(<any context info you think helpful>));
}
});
Yes, it's possible.
#Override
public void onFailure(Throwable arg0) {
throw new RuntimeException(arg0);
}
This code is absolutely valid. But to what purpose are you creating and throwing a new instance of RuntimeException?
At that if you write
new RuntimeException("Error message")
you lose all information about occurred exception.
And don't forget that in GWT all calls from client to a remote service are handled asynchronously. And the onFailure() callback method are called immediatly when an asynchronous call fails to complete normally.
No, you can't. Well, you can throw the exception, but it won't be handled by the catch block you defined, since the AsyncCallback is an anonymous class that does not run in the same scope and is not called at the same time as your catch block.
You can however try to use GWT.setUncaughtExceptionHandler(), see the details at http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/core/client/GWT.html.