jeudi 30 juillet 2020

Delegate complicated exception handling to separate class?

I've been trying to follow the default rule of using composition over inheritance to share functionality between classes, but have run into a situation where an existing base class' method's very complicated exception handling now needs to be specialized for certain sub-classes (multiple).

So the exception handling in the base class is something like:

try {
    doSomething()
} catch (HttpClientErrorException ex) {
    // complicated logic
} catch (HttpServerErrorException ex) {
    // complicated logic
} catch (RestClientException ex) {
    // complicated logic
} catch (Exception ex) {
    throw ex;
}

But now for certain extensions of this base class, we want to first check for a certain type of HttpClientErrorException and do special logic instead. Instead of parenting the classes that need this special logic to a new base class that extends the original base class, should we consider creating a separate exception handler interface and injecting it into the base class?

An implementation of the interface would implement handleException which might look something like:

public void handleException(Exception ex) {
    if (ex instanceof HttpClientErrorException ) {
        // complicated logic
    }
    ..etc..
}

Is this considered bad practice? Are there drawbacks I'm not seeing? If so, what is the preferred way to deal with this situation?

Aucun commentaire:

Enregistrer un commentaire