Java Reference
In-Depth Information
current
.
setLastName
(
update
.
getLastName
());
current
.
setStreet
(
update
.
getStreet
());
current
.
setState
(
update
.
getState
());
current
.
setZip
(
update
.
getZip
());
current
.
setCountry
(
update
.
getCountry
());
}
}
In
ex06_1
, our
getCustomer()
and
updateCustomer()
methods threw a
javax.ws.rs.WebApplicationException
. We've replaced this exception with our own
custom class,
CustomerNotFoundException
:
src/main/java/com/restfully/shop/services/CustomerNotFoundException.java
public
public class
class
CustomerNotFoundException
CustomerNotFoundException
extends
extends
RuntimeException
{
public
public
NotFoundException
(
String s
)
{
super
super
(
s
);
}
}
There's nothing really special about this exception class other than it inherits from
java.lang.RuntimeException
. What we are going to do, though, is map this thrown ex-
ception to a
Response
object using an
ExceptionMapper
:
src/main/java/com/restfully/shop/services/CustomerNotFoundExceptionMapper.java
@Provider
public
public class
class
NotFoundExceptionMapper
NotFoundExceptionMapper
implements
implements
ExceptionMapper
<
CustomerNotFoundException
>
{
public
public
Response
toResponse
(
NotFoundException exception
)
{
return
return
Response
.
status
(
Response
.
Status
.
NOT_FOUND
)
.
entity
(
exception
.
getMessage
())
.
type
(
"text/plain"
).
build
();
}
}
When a client makes a GET request to a customer URL that does not exist, the
CustomerRe-
source.getCustomer()
method throws a
CustomerNotFoundException
. This exception is
caught by the JAX-RS runtime, and the
NotFoundExceptionMapper.toResponse()
method
is called. This method creates a
Response
object that returns a 404 status code and a plain-
text error message.