Skip to content

Commit

Permalink
Fail soft on malformed Json, workaround for #7
Browse files Browse the repository at this point in the history
  • Loading branch information
marvk committed Mar 23, 2019
1 parent 8e0e118 commit 2998925
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import lombok.extern.log4j.Log4j2;
import net.marvk.chess.lichess4j.model.Challenge;
import net.marvk.chess.lichess4j.model.EventResponse;
Expand Down Expand Up @@ -43,7 +44,7 @@ protected void onCharReceived(final CharBuffer buf, final IOControl ioControl) {
log.trace("Received event response:\n" + response);

Arrays.stream(response.split("\n"))
.map(line -> GSON.fromJson(line, EventResponse.class))
.map(EventResponseConsumer::safeJson)
.forEach(this::acceptEvent);
}

Expand Down Expand Up @@ -76,4 +77,13 @@ protected void onResponseReceived(final HttpResponse response) {
protected Boolean buildResult(final HttpContext context) {
return Boolean.TRUE;
}

private static EventResponse safeJson(final String line) {
try {
return GSON.fromJson(line, EventResponse.class);
} catch (final JsonParseException e) {
log.error("Failed to parse line:\n " + line, e);
return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import lombok.extern.log4j.Log4j2;
import net.marvk.chess.core.board.UciMove;
import net.marvk.chess.lichess4j.model.*;
Expand Down Expand Up @@ -55,7 +56,7 @@ protected void onCharReceived(final CharBuffer buf, final IOControl ioControl) {
log.trace("Received game state response:\n" + response);

Arrays.stream(response.split("\n"))
.map(line -> GSON.fromJson(line, GameStateResponse.class))
.map(GameStateResponseConsumer::safeJson)
.forEach(this::acceptGameStateResponse);
}

Expand Down Expand Up @@ -96,4 +97,12 @@ protected Boolean buildResult(final HttpContext httpContext) {
return Boolean.TRUE;
}

private static GameStateResponse safeJson(final String line) {
try {
return GSON.fromJson(line, GameStateResponse.class);
} catch (final JsonParseException e) {
log.error("Failed to parse line:\n " + line, e);
return null;
}
}
}

0 comments on commit 2998925

Please sign in to comment.