Java Reference
In-Depth Information
The ExceptionMappers
The
EntityManager.getReference()
method is used by various EJBs in this example to
locate objects within the database. When this method cannot find an object within the data-
base, it throws a
javax.persistence.EntityNotFoundException
. If we deployed this
code as is, JAX-RS would end up eating this exception and returning a 500, “Internal Server
Error,” to our clients if they tried to access an unknown object in the database. The 404, “Not
Found,” error response code makes a lot more sense to return in this scenario. To facilitate
this, a JAX-RS
ExceptionMapper
is used. Let's take a look:
ejb/src/main/java/com/restfully/shop/services/EntityNotFoundExceptionMapper.java
@Provider
public
public class
class
EntityNotFoundExceptionMapper
EntityNotFoundExceptionMapper
implements
implements
ExceptionMapper
<
EntityNotFoundException
>
{
public
public
Response
toResponse
(
EntityNotFoundException exception
)
{
return
return
Response
.
status
(
Response
.
Status
.
NOT_FOUND
).
build
();
}
}
This class catches
EntityNotFoundExceptions
and generates a 404 response.
Changes to Application class
The
ShoppingApplication
class has been simplified a bit. Because all of our code is imple-
mented as EJBs, there's no special registration we need to do in our
Application
class.
Here's what it looks like now:
war/src/main/java/com/restfully/shop/services/ShoppingApplication.java
@ApplicationPath
(
"/services"
)
public
public class
class
ShoppingApplication
ShoppingApplication
extends
extends
Application
{
}
The Wildfly application server will scan the WAR for any annotated JAX-RS classes and
automatically deploy them. In this deployment, all of our JAX-RS services are EJBs and
contained in the
WEB-INF/classes
folder of our WAR.
The Client Code
Let's take a look at the client code:
ear/src/test/java/com/restfully/shop/test/ShoppingTest.java