I'm using the library https://github.com/MrStahlfelge/gdx-websockets with LibGDX and Java.
I'm having trouble dealing with errors occurring in the onMessage method.
It seems to silently suppress all errors even if I set setSendGracefully(false).
private WebSocket socket;
socket = WebSockets.newSocket(WebSockets.toSecureWebSocketUrl("myDomain.com", 8080));
socket.setSendGracefully(false);
socket.addListener(new WebSocketListener() {
@Override
public boolean onOpen(WebSocket webSocket) {
Gdx.app.log(TAG, "onOpen"); // line reached
return false;
}
@Override
public boolean onClose(WebSocket webSocket, int closeCode, String reason) {
Gdx.app.log(TAG, "onClose"); // line reached
return false;
}
public boolean onMessage(WebSocket webSocket, String packet) {
Gdx.app.log(TAG, "onMessage: " + packet); // line reached
Vector2 vtest = null;
try {
vtest.x = 1;
}
catch (Exception ex) {
// line not reached
Gdx.app.log(TAG, "error onMessage: " + ex.getCause().getMessage() + "; " + ex.getMessage());
} catch (Throwable throwable) { // Catch both exceptions and errors
// line not reached
Gdx.app.error(TAG, "error onMessage:", throwable);
}
return false;
}
@Override
public boolean onError(WebSocket webSocket, Throwable error) {
// it never reaches this method
Gdx.app.log(TAG, "onError: " + error.getCause().getMessage() + "; " + error.getMessage());
return false;
}
});
socket.connect();
All others Gdx.app.log lines print out the log.
Do you have any suggestions? Am I doing something wrong/leaving something out?
Thanks
It is because the NullPointerException
that is being throw by vtest.x = 1;
does not have an underlying cause, so getCause()
returns null, causing another NullPointerException
to be throw when you try to log.
// ex.getCause() will return null here, causing the log statement to throw and not log anything
Gdx.app.log(TAG, "error onMessage: " + ex.getCause().getMessage() + "; " + ex.getMessage());
Consider using
Gdx.app.error(TAG", "some_message", ex);
instead of Gdx.app.log
to log Exception
s.