【发布时间】:2012-02-26 17:58:06
【问题描述】:
我正在编写一个包含 REST API 的库。我正在创建的包装器使用 GSON 将 json 反序列化到我的对象中。基本上是这样的……
public Post getPost(url) throws IOException {
String jsonString = httpClient.get(url);
Post p = gson.fromJson(jsonString, Post.class);
// return Post to client and let client do something with it.
}
如果我理解正确的话,IOException 是一个检查异常。我告诉我的客户:嘿,伙计——你最好小心并从这个异常中恢复过来。现在我的客户可以将调用包装在 try/catch 中,并确定如果出现网络故障该怎么办。
GSON fromJson() 方法抛出 JsonSyntaxException。我相信这在 Java 世界中是未经检查的,因为它的超类之一是 RuntimeException,也因为我不需要添加 try/catch 或像 IOException 这样的其他“抛出”。
假设我到目前为止所说的是正确的 - API 和客户端应该如何处理这种情况?如果 json 字符串是垃圾,我的客户端将由于 JsonSyntaxException 而失败,因为它没有被选中。
// Client
PostService postService = new PostService();
try{
Post p = postService.getPost(urlString);
// do something with post
}catch (IOException){
// handle exception
}
// ok, what about a JsonSyntaxException????
处理这些情况的最佳方法是什么?
【问题讨论】:
标签: java exception-handling gson