0

I have a bunch of entities that I do CRUD on, ex. Car, Boat, Banana, etc. All of these have similar exceptions that I throw when something goes wrong. For example, if I'm trying to retrieve something but it doesn't exist I throw an EntityNotFoundException (defined by me, not jpa), or if I'm creating something but it hits some unique constraint I throw an EntityAlreadyExistsException.

What I'm worried about is that I have (or will have) 60 classes that are coupled to these exceptions I defined in another utility library class. If the jar is missing then there's red everywhere, so I can visually see the coupling.

Is there a way around this? I'm reusing these exceptions because they're all for the same purpose and I'd hate to duplicate code (ex: duplicate the exceptions for every package), so in my mind it makes sense that it'd be used everywhere, but something about it makes me feel uneasy.

Thanks.

GuitarStrum
  • 713
  • 8
  • 24
  • If your custom Exceptions extends IOException (or anything else) you could maybe simply catch IOExceptions in upper layers of your code ? But anyway, I'd say the proper way to handle these case would be to catch your custom exceptions in an AbstractCRUDService and handle or rethrow them as a more API-friendly exception, namely an IOException. – Jeremy Grand Mar 21 '17 at 12:38
  • As I see it you have 2 options. 1) Create a super class for your custom exceptions (or just use Exception as the superclass for your exceptions) 2) Create a single custom exception but add different messages (constants) for different exceptions. – dsp_user Mar 21 '17 at 13:06
  • My classes would still be coupled to that big exception though, whether I have one custom exception or ten. Another reason I don't want to use one larger exception is because I'll send back different error codes (ex: NO_CONTENT for EntityNotFound, BAD_REQUEST for missing client input, etc) – GuitarStrum Mar 21 '17 at 13:15

0 Answers0