我正在使用Gson处理Json响应。有时我得到一个例外,但不幸的是我没有足够的背景来确定问题的确切位置。
JsonReader创建如下:
private JsonReader getJsonReader(final HttpEntity entity) throws IOException {
final InputStreamReader reader = new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8);
return new JsonReader(reader);
}
我的想法是继承InputStreamReader
并记录通过它的所有内容,以便在抛出异常时获得更多上下文。
有更好的方法吗?
答案 0 :(得分:0)
我创建了以下两个子类:
public class LoggingReader extends InputStreamReader {
private char[] lastRead;
public LoggingReader(final InputStream inputStream, final Charset charset) {
super(inputStream, charset);
}
@Override
public int read(final char[] chars, final int i, final int i1) throws IOException {
final int result = super.read(chars, i, i1);
lastRead = chars;
return result;
}
public String getLastRead() {
return new String(lastRead);
}
}
public class LoggingJsonReader extends JsonReader {
private final LoggingReader reader;
public LoggingJsonReader(final LoggingReader in) {
super(in);
this.reader = in;
}
public String getLastRead() {
return reader.getLastRead();
}
}
现在当抛出异常时,我会这样做:
catch (Exception ex) {
if (reader instanceof LoggingJsonReader) {
LoggingJsonReader lReader = (LoggingJsonReader) reader;
log.error(lReader.getLastRead());
}