1. Using WebApplicaitonException exceptions to report errors
JAX-RS提供了WebApplicationException,针对resource method创建异常,WebApplicationException包含一个
Reponse Object,该对象定义了返回给request的Entity Body, 如果没有Entity Body,该对象同时提供了一种机制
用于指定HTTP Status Code.
(1) Setting the status code returned to the client
WebApplicationException(int status);
WebApplicationException(java.lang.Throwable cause, int status);
WebApplicationException(javax.ws.rs.core.Response.Status status);
WebApplicationException(java.lang.Throwable cause, javax.ws.rs.core.Response.Status status);
(2) Providing an entity body
import javax.ws.rs.core.Response;
import javax.ws.rs.WebApplicationException;
import org.apache.cxf.jaxrs.impl.ResponseBuilderImpl;
ResponseBuilderImpl builder = new ResponseBuilderImpl();
builder.status(Response.Status.CONFLICT);
builder.entity("The requested resource is conflicted.");
Response response = builder.build();
throw WebApplicationException(response);
(3) Extending the generic exception
public class ConflicteddException extends WebApplicationException{
public ConflictedException(String message){
ResponseBuilderImpl builder = new ResponseBuilderImpl();
builder.status(Response.Status.CONFLICT);
builder.entity(message);
super(builder.build());
}
}
throw ConflictedException("The requested resource is conflicted.");
2. Mapping exceptions to responses
(1) How exception mappers are selected
(2) Implementing an exception mapper
(3) Registering an exception mapper