简体   繁体   中英

Best practice for handling multiple exceptions in multiple methods same way in Java

I have a class ServerApi with methods callApiA , callApiB , ... Each of this methods returns subclass of the ServerApiResponse . Communication to server is managed by HttpClient .

There are many things that could go wrong, for example:

  • server has crashed
  • no Internet connection
  • timeout

Also server could send meta-response, for example:

  • session expired
  • server overloaded

Now I need to handle all of this situations in one place. Is it okey to catch Exception in all callApiX methods, and handle it in one place by checking exception type by instance of method or is there any better solution?

... callApiA(...){
    try{
        ...
    } catch(Exception e){
        return handleApiCallException(e);
    }
}

... callApiB(...){
    try{
        ...
    } catch(Exception e){
        return handleApiCallException(e);
    }
}

...

... callApiX(...){
    try{
        ...
    } catch(Exception e){
        return handleApiCallException(e);
    }
}

... handleAPiCallException(Exception e){
    if(e instance of IOException){
        ...
    } else if(e instanceof ...){
        ...
    } ...
}

You don't always want to return something when you catch an exception . I would do something like that:

catch (IOException | AnotherException | ... e) {
    //Handle exceptions here..
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM