解析DBXException java的最佳方法
因此,我最近提出了如何处理Dropbox API异常的问题。我了解到我必须将DBXEception解析为它的一部分,其中有很多。现在考虑到这一点,我想知道处理这一问题的最佳方式是什么 目前,我计划使用instanceof并像这样检查,如果我想让程序再试一次,它将返回true,程序将再试一次,可能会使用服务器请求进行指数退避解析DBXException java的最佳方法,java,exception-handling,dropbox,dropbox-api,Java,Exception Handling,Dropbox,Dropbox Api,因此,我最近提出了如何处理Dropbox API异常的问题。我了解到我必须将DBXEception解析为它的一部分,其中有很多。现在考虑到这一点,我想知道处理这一问题的最佳方式是什么 目前,我计划使用instanceof并像这样检查,如果我想让程序再试一次,它将返回true,程序将再试一次,可能会使用服务器请求进行指数退避 public boolean parseDBX(DbxException e) { if(e instanceof AccessErrorExcept
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();
}
}
}
for(inti=0;i++){
试一试{
ListFolderResult=client.files().listFolder(“/Saves/”+prefName);
while(true){
for(元数据:result.getEntries()){
System.out.println(metadata.getPathLower());
//元数据。
}
如果(!result.getHasMore()){
打破
}
结果=client.files().listFolderContinue(result.getCursor());
}
}捕获(ListFolderErrorException e){
createDefFolder();
}捕获(DbxException e){
if(codeHandler.parse(e)&&i最好的方法是通过捕获适当类型的异常来避免“解析”异常:
try {
...
} catch (AccessErrorException aee) {
...
} catch (DbxApiException dae) {
...
}
如果不需要,您可以将自己的整数ID与每个异常类型相关联,将其放入映射
,并在解析
方法中使用它来区分开关中的子类型
:
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()) {
...
}
}
}
staticmap parseId=newhashmap();
静止的{
parseId.put(AccessErrorException.class,1);
parseId.put(DbxApiException.class,2);
...
}
...
公共void parseDBX(DbxException e){
整数id=parseId.get(e.getClass());
如果(id!=null){
开关(id.intValue()){
...
}
}
}
在哪里调用parseDBX()
方法?如果在catch
块中,最好只为每个子类型添加一个catch
块?可能更多(code)上下文会有帮助。谢谢,我计划使用第二个选项,这样我就不会有太多的catch块,但是,这些选项中的任何一个都会对性能有好处吗。@Austin第一个选项会使用更少的CPU周期,因为分派是直接由JVM完成的。它不会对性能产生明显的影响,因为决定分派到在异常处理过程中,特定的代码块是一个相对不重要的步骤,特别是当异常是网络调用的结果时。