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 WebApplica
Why to use one possibility over the other since the result is the same?
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 an ArrayIndexOutOfBoundsException
, acces something you are not allowed to and get a SecurityException
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.g ProductNotFoundException extends WebApplicationException { ... }
, AccessDeniedException extends WebApplicationException { ... }
or reusing exceptions with an exception mapper).
It's then cleaner to throw new ProductNotFoundException()
or throw new AccessDeniedException()
and let the framework handle it instead of building a Response every time and later follow the details used to build it to figure out what's happening in that section of code.