Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApplicationException vs Response

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?

like image 782
manash Avatar asked Nov 13 '12 10:11

manash


People also ask

What is WebApplicationException?

public class WebApplicationException extends RuntimeException. Runtime exception for applications. This exception may be thrown by a resource method, provider or StreamingOutput implementation if a specific HTTP error response needs to be produced. Only effective if thrown prior to the response being committed.

What is client error exception?

Answer: Client exception errors mean there's a problem on the front end (i.e. a bug or unexpected condition in the JavaScript for the IDE in the browser).


1 Answers

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.

like image 107
Bogdan Avatar answered Oct 07 '22 18:10

Bogdan