Search code examples
javaexceptiondropboxdropbox-api

Best way to parse DBXException java


So I recently asked the question of how to handle Dropbox API Exceptions here. I learned that I would have to parse the DBXEception into its subclasses which there are many of. Now Thinking about this I am wondering what would be the best way to go about handling this.

Currently I plan on using instanceof and checking like this if I want the program to try again it will return true and the program will try again maybe with a exponential backoff with server request

public boolean parseDBX(DbxException e)
    {
        if(e instanceof AccessErrorException) {//handle Error

        }else if (e instanceof DbxApiException) {//handle Error

        }etc
    }

It would be called in a catch block like this

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();
                            }


        }
        }

So My Question is there a way to use a switch statement instead(From what I have found the answer is no), and if not, is there a better way to handle checking for the type of exception.


Solution

  • The best approach is to avoid "parsing" the exception at all by catching exceptions of the appropriate type:

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

    In cases when this is not desirable you could associate your own integer ID with each exception type, put it in a Map, and use it in your parse method to distinguish among subtypes in a 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()) {
                ...
            }
        }
    }