3

Say I have an REST API for creating users in an application. The request goes to a controller, which marshals the request data into a domain object, and passes it to a service to create a user.

Now, there are certain uniqueness constraints on a user. If the user service receives a request to create a duplicate user, is it appropriate to throw an Exception at this point, e.g. DuplicateUserException, or is there a better way of handling something that is a predictable error case, i.e. not an exceptional circumstance)?

The goal here would be to provide as much detail to the API client as possible, to allow them to correct their mistake.

  • REST API client? or other Java coder using the library? – user40980 Mar 1 '16 at 17:43
4

There are two extreme positions that can be taken here:

  1. Exceptions must truly be exceptional. There is nothing even remotely exceptional about trying to add an existing user. Therefore, the failure should be indicated via a return value.
  2. Unless a method can run through the optimal functional path (in this case, add a new user as that user doesn't yet exist), throw an exception. Exceptions aren't exceptional, they simply represent where the non-optimal path could not be followed. Error codes should never be returned; this should always be handled by exceptions.

As with most things, the pragmatic solution is somewhere between these two extremes. As you are providing a REST API, even if an exception is thrown, it still needed to be caught, possibly decoded and bundled up as a return result to the client, otherwise they may get no response. In this instance, it may therefore be simpler to return a simpler error message back up through the various layers. There may be good reasons though why the exception route will work better (if there are many layers, throwing an exception simplifies things sometimes). So weigh up the pros and cons and pick the solution that best fits your particular case.

  • Yes, the controller would definitely be responsible for catching any exceptions thrown to ensure the client receives an intelligible response. The benefit of exceptions is, as you said, that it simplifies communication of errors through the various application layers. – evanjdooner Mar 1 '16 at 15:08
5

Exceptional cases don't have to be exceptionally rare. Discovering that your desired username is already taken is an exceptional case in the workflow of "ask to create new user; new user is created". Throwing an exception here is absolutely fine and normal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.