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;
}
try {
onReceivePayload(payload);
} catch (Throwable t) {
trySendAsJson(new ErrorPayload("Error handling payload: " + t));
if (t instanceof Exception)
logError("Error handling payload", t);
else
throw t;
if (payload instanceof ErrorPayload errorPayload) {
try {
onReceiveErrorPayload(errorPayload);
} catch(Exception e) {
logError("Error while handling received error payload", e);
}
}
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);
/**
* 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.
* The connection is closed after this method call.

View File

@ -49,12 +49,12 @@ public class PayloadRegistry {
public static Payload fromString(String message) {
String[] split = message.split(Pattern.quote(PAYLOAD_TYPE_SEPARATOR), 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]);
if (detectedClass == null) {
throw new IllegalArgumentException("Unrecognized data type '" + split[0] + "'.");
throw new IllegalArgumentException("Unrecognized data type " + split[0] + ".");
}
try {