Handle reception of ErrorPayload in WS.

This commit is contained in:
Marc Baloup 2023-03-19 17:25:14 +01:00
parent e4a5bf0eac
commit 2bc60df11c
2 changed files with 30 additions and 10 deletions

View File

@ -32,15 +32,26 @@ public interface AbstractWS {
return; return;
} }
try { if (payload instanceof ErrorPayload errorPayload) {
onReceivePayload(payload); try {
} catch (Throwable t) { onReceiveErrorPayload(errorPayload);
trySendAsJson(new ErrorPayload("Error handling payload: " + t)); } catch(Exception e) {
if (t instanceof Exception) logError("Error while handling received error payload", e);
logError("Error handling payload", t); }
else
throw t;
} }
else {
try {
onReceivePayload(payload);
} catch (Throwable t) {
trySendAsJson(new ErrorPayload("Error while handling your payload: " + t));
if (t instanceof Exception)
logError("Error while handling received payload", t);
else
throw t;
}
}
} }
/** /**
@ -62,6 +73,15 @@ public interface AbstractWS {
*/ */
void onReceivePayload(Payload payload); void onReceivePayload(Payload payload);
/**
* Called on reception of a valid {@link ErrorPayload}.
* @param error the received {@link ErrorPayload}.
* @implNote default implementation will log the received error.
*/
default void onReceiveErrorPayload(ErrorPayload error) {
logError("Received the following error from the remote side: " + error.message, error.throwable);
}
/** /**
* Called on reception of a websocket Close packet. * Called on reception of a websocket Close packet.
* The connection is closed after this method call. * The connection is closed after this method call.

View File

@ -49,12 +49,12 @@ public class PayloadRegistry {
public static Payload fromString(String message) { public static Payload fromString(String message) {
String[] split = message.split(Pattern.quote(PAYLOAD_TYPE_SEPARATOR), 2); String[] split = message.split(Pattern.quote(PAYLOAD_TYPE_SEPARATOR), 2);
if (split.length != 2) { if (split.length != 2) {
throw new IllegalArgumentException("Malformed message: does not respect format '<type>" + PAYLOAD_TYPE_SEPARATOR + "<jsonObject>'."); throw new IllegalArgumentException("Malformed message: does not respect format <type>" + PAYLOAD_TYPE_SEPARATOR + "<jsonObject>.");
} }
Class<? extends Payload> detectedClass = payloadClasses.get(split[0]); Class<? extends Payload> detectedClass = payloadClasses.get(split[0]);
if (detectedClass == null) { if (detectedClass == null) {
throw new IllegalArgumentException("Unrecognized data type '" + split[0] + "'."); throw new IllegalArgumentException("Unrecognized data type " + split[0] + ".");
} }
try { try {