Among all the possibilities to return a response to the client in a REST service, I've seen two possibilities that look equivalent: throwing a WebApplicationException
(possibly using a Response
instance) or returning a Response
instance.
Why to use one possibility over the other since the result is the same? Is this related to the REST framework used that may be configured to react differently between exceptions and regular responses?
Maybe because as a (Java) programmer you are accustomed with throwing exceptions when particular rules of the application are broken? Convert some string to a number and you might get a
NumberFormatException
, use a wrong index in an array and you get anArrayIndexOutOfBoundsException
, acces something you are not allowed to and get aSecurityException
etc. You are used to throwing exceptions when the "regular response" can't be created (be it from wrong input or some processing error).When you can't return the regular response, you must return an error response to the client. You can do that with either throwing the exception or building the response by hand. It's the same thing for your client, but it's not the same thing for your server side code.
Throwing the exception makes your code cleaner, easier to reason about and thus easier to understand. The idea is to subclass the
WebApplicationException
and create your own meaningful exceptions out of it (e.gProductNotFoundException extends WebApplicationException { ... }
,AccessDeniedException extends WebApplicationException { ... }
or reusing exceptions with an exception mapper).It's then cleaner to
throw new ProductNotFoundException()
orthrow new AccessDeniedException()
and let the framework handle it instead of building aResponse
every time and later follow the details used to build it to figure out what's happening in that section of code.