We are building a Java SDK to simplify the access to one of our services that provide a REST API. This SDK is to be used by 3rd-party developers. I am struggling to find the bes
The solution may vary depending on your needs.
If it is supposed that there could appear unpredictable new exception types in the future, your second solution with checked exception hierarchy and method that throw their superclass RestServiceException
is the best one. All known subclasses should be listed in the javadoc like Subclasses: {@link UnauthenticatedException}, ...
, to let developers know what kind of of exceptions there could hide. It should be noticed that if some method could throw only few exceptions from this list, they should be described in the javadoc of this method using @throws
.
This solution is also applicable in the case when all appearances of RestServiceException
means that any of it's subclasses could hide behind it. But in this case, if RestServiceException
subclasses hasn't their specific fields and methods, your first solution is preferrable, but with some modifications:
public class RestServiceException extends Exception {
private final Type type;
public Type getType();
...
public static enum Type {
UNAUTHENTICATED,
UNAUTHORISED,
NOT_FOUND;
}
}
Also there is a good practice to create alternative method that will throw unchecked exception that wraps RestServiceException
exeption itself for usage within ‘all-or-nothing’ business logic.
public Photo getPhotoUnchecked(String photoID) {
try {
return getPhoto(photoID);
catch (RestServiceException ex) {
throw new RestServiceUncheckedException(ex);
}
}