所以我最近问了如何处理Dropbox API异常的问题here。我了解到我必须将DBXEception解析为subclasses,其中有很多。现在考虑到这一点,我想知道处理这个问题的最佳方法是什么。
目前我打算使用instanceof并像这样检查如果我希望程序再次尝试它将返回true并且程序将再次尝试使用服务器请求的指数退避
public boolean parseDBX(DbxException e)
{
if(e instanceof AccessErrorException) {//handle Error
}else if (e instanceof DbxApiException) {//handle Error
}etc
}
它将在像这样的catch块中调用
for(int i =0;;i++) {
try {
ListFolderResult result = client.files().listFolder("/Saves/"+prefName);
while (true) {
for (Metadata metadata : result.getEntries()) {
System.out.println(metadata.getPathLower());
//metadata.
}
if (!result.getHasMore()) {
break;
}
result = client.files().listFolderContinue(result.getCursor());
}
} catch (ListFolderErrorException e) {
createDefFolder();
} catch (DbxException e) {
if(codeHandler.parse(e)&&i<10) {
continue;
}else {
log.write("Error 5332490: a problem was encountered while trying to check for the root file"+e.getMessage());
throw new IOException();
}
}
}
所以我的问题是有一种方法可以使用switch语句(从我发现的答案是否定的),如果没有,是否有更好的方法来处理异常类型的检查。
答案 0 :(得分:1)
最好的方法是避免&#34;解析&#34;通过捕获适当类型的异常来完成例外:
try {
...
} catch (AccessErrorException aee) {
...
} catch (DbxApiException dae) {
...
}
如果不希望这样,您可以将自己的整数ID与每种异常类型相关联,将其放在Map
中,并在parse
方法中使用它来区分switch
中的子类型{1}}:
static Map<Class,Integer> parseId = new HashMap<>();
static {
parseId.put(AccessErrorException.class, 1);
parseId.put(DbxApiException.class, 2);
...
}
...
public void parseDBX(DbxException e) {
Integer id = parseId.get(e.getClass());
if (id != null) {
switch (id.intValue()) {
...
}
}
}