Java Reference
In-Depth Information
Working
with
Exceptions
and
Response
Status
Codes
Problem
You want your service to throw exceptions under certain conditions, and deal with them ap-
propriately on the client.
Solution
Create a response with the status code you want to set, and then set it into a WebApplica-
tionException instance and throw it out of the method.
Discussion
Example 8-30 shows the class that handles this.
Example8-30.Creating an exception and setting your own HTTP status
package com.soacookbook.rest.response;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
@Path("statuscode")
public class CustomStatusCode {
@GET
public Response doGet(){
Response.ResponseBuilder responseBuilder =
Response.status(Response.Status.BAD_REQUEST);
Response response = responseBuilder.build();
throw new WebApplicationException(response);
}
}
The WebApplicationException is a runtime exception that you can use to issue clients
standard HTTP response codes. The primary downside to the class is that it doesn't allow you
to set your own message. The default message and description will be sent with the exception
to clients. In the case of BAD_REQUEST , there is no message, and the description is merely “The
Search WWH ::




Custom Search