Вы находитесь на странице: 1из 2

5.

Exception Handling:
Now we need to discuss what happens if an error occurs when you use an invocation
style that automatically unmarshalls the response. Consider this example:

Customer customer = client.target("http://commerce.com/customers/123")


.accept("application/json")
.get(Customer.class);

In this scenario, the client framework converts any HTTP error code into one of the
exception hierarchy exceptions discussed in Exception Hierarchy. We can then catch
these exceptions in our code to handle them appropriately:
try {
Customer customer = client.target("http://commerce.com/customers/123")
.accept("application/json")
.get(Customer.class);
} catch(NotAcceptableException notAcceptable) {
...
} catch (NotFoundException notFound) {
...
}

If the server responds with an HTTP error code not covered by a specific JAX-RS
exception, then a general-purpose exception is thrown.
ClientErrorException covers any error code in the 400s.
ServerErrorException covers any error code in the 500s.
This invocation style will not automatically handle server redirects that is, when the
server sends one of the HTTP 3xx redirection response codes. Instead, the JAX-RS
Client API throws a RedirectionException from which we can obtain the Location URL
to do the redirect yourself.
For example:
WebTarget target = client.target("http://commerce.com/customers/123");
boolean redirected = false;
Customer customer = null;
do {
try {
customer = target.accept("application/json")
.get(Customer.class);
} catch (RedirectionException redirect) {
if (redirected) throw redirect;
redirected = true;
target = client.target(redirect.getLocation());
}
} while (customer == null);

In this example, we loop if we receive a redirect from the server. The code makes
sure that we allow only one redirect by checking a flag in the catch block. We change
the WebTarget in the catch block to the Location header provided in the server’s
response. We might want to massage this code a little bit to handle other error
conditions.

Response response = client.target("http://commerce.com/customers/123")


.accept("application/json")
.get();
if (response.getStatusCode==404) {
throw new NotFoundException("Invalid customerId plz enter valid customerId");
// this exception management is used in the client as well to display the proper
messages to the

client side web-appl uses.


}

Вам также может понравиться