解析DBXException java的最佳方法

问题描述 投票:1回答:1

所以我最近问了如何处理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语句(从我发现答案是否定的),如果没有,是否有更好的方法来处理异常类型的检查。

java exception-handling dropbox dropbox-api
1个回答
1
投票

最好的方法是通过捕获适当类型的异常来避免“解析”异常:

try {
    ...
} catch (AccessErrorException aee) {
    ...
} catch (DbxApiException dae) {
    ...
}

如果不希望这样,您可以将自己的整数ID与每种异常类型相关联,将其放在Map中,并在parse方法中使用它来区分switch中的子类型:

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()) {
            ...
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.