[英]How can I make lightcouch output proper errors when deserializing json?
我有一個帶有大型復雜json對象的大型CouchDB。 反序列化它們時,有時會出錯,因為文檔格式不正確。
可悲的是,gson封裝不提供以下信息:
com.google.gson.JsonSyntaxException:
java.lang.IllegalStateException: Expected BLAH but was BLUB
而且,我必須開始調試整個應用程序,以查找哪個文檔無法解析。
我想獲取發生異常時反序列化的父文檔,以便我可以記錄其ID。
那可能嗎?
因此,到目前為止,我發現的方法是創建一個記錄錯誤的TypeAdapterFactory並嘗試創建空對象或至少返回null。 盡管我在對象層次結構的最低級別遇到錯誤,這還是很好的(例如,在無法解析的那一點,因此我缺少有關它是哪個文檔的信息。)
這是代碼:
public class RobustTypeAdapterFactory implements TypeAdapterFactory {
private static final Logger LOG = LoggerFactory.getLogger(RobustTypeAdapterFactory.class);
@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
return new TypeAdapter<T>() {
@Override
public void write(final JsonWriter out, final T value) throws IOException {
delegate.write(out, value);
}
@SuppressWarnings("unchecked")
@Override
public T read(final JsonReader in) throws IOException {
try {
return delegate.read(in);
} catch (IOException | IllegalStateException | JsonSyntaxException e) {
LOG.info("Could not parse value for {}", type.getRawType());
in.skipValue();
try {
// try to create empty object
return (T) type.getRawType().newInstance();
} catch (ReflectiveOperationException e1) {
// we couldn't create an empty object, so we return null
return null;
}
}
}
};
}
}
有更好的主意嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.