Java Reference
In-Depth Information
list
.
add
(
new
new
Customer
(...));
GenericEntity entity
=
new
GenericEntity
<
List
<
Customer
>>(
list
){};
return
return
Response
.
ok
(
entity
).
build
();
}
The
GenericEntity
class is a Java generic template. What you do here is create an anonym-
ous class that extends
GenericEntity
, initializing the
GenericEntity
's template with the
generic type you're using. If this looks a bit magical, it is. The creators of Java generics
made things a bit difficult, so we're stuck with this solution.
Exception Handling
Errors can be reported to a client either by creating and returning the appropriate
Response
object or by throwing an exception. Application code is allowed to throw any checked
(classes extending
java.lang.Exception
) or unchecked (classes extending
java.lang.RuntimeException
) exceptions they want. Thrown exceptions are handled by
the JAX-RS runtime if you have registered an exception mapper. Exception mappers can
convert an exception to an HTTP response. If the thrown exception is not handled by a map-
per, it is propagated and handled by the container (i.e., servlet) JAX-RS is running within.
JAX-RS also provides the
javax.ws.rs.WebApplicationException
. This can be thrown
by application code and automatically processed by JAX-RS without having to write an ex-
plicit mapper. Let's look at how to use the
WebApplicationException
first. We'll then ex-
amine how to write your own specific exception mappers.
javax.ws.rs.WebApplicationException
JAX-RS has a built-in unchecked exception that applications can throw. This exception is
preinitialized with either a
Response
or a particular status code:
public
public class
class
WebApplicationException
WebApplicationException
extends
extends
RuntimeException
{
public
public
WebApplicationException
() {...}
public
public
WebApplicationException
(
Response response
) {...}
public
public
WebApplicationException
(
int
int
status
) {...}
public
public
WebApplicationException
(
Response
.
Status
status
) {...}
public
public
WebApplicationException
(
Throwable cause
) {...}
public
public
WebApplicationException
(
Throwable cause
,
Response response
) {...}
public
public
WebApplicationException
(
Throwable cause
,
int
int
status
) {...}
public
public
WebApplicationException
(
Throwable cause
,
Response
.
Status
status
) {...}