避免导入 Jackson 类但只坚持纯 JAX-RS 类我创建这样的 json 异常包装器。
创建 ExceptionInfo 包装器并子类化各种异常状态类型。
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
@XmlRootElement
public class ExceptionInfo {
private int status;
private String msg, desc;
public ExceptionInfo(int status, String msg, String desc) {
this.status=status;
this.msg=msg;
this.desc=desc;
}
@XmlElement public int getStatus() { return status; }
@XmlElement public String getMessage() { return msg; }
@XmlElement public String getDescription() { return desc; }
}
- - - -
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.WebApplicationException;
/**
* Create 404 NOT FOUND exception
*/
public class NotFoundException extends WebApplicationException {
private static final long serialVersionUID = 1L;
public NotFoundException() {
this("Resource not found", null);
}
/**
* Create a HTTP 404 (Not Found) exception.
* @param message the String that is the entity of the 404 response.
*/
public NotFoundException(String msg, String desc) {
super(Response.status(Status.NOT_FOUND).entity(
new ExceptionInfo(Status.NOT_FOUND.getStatusCode(), msg, desc)
).type("application/json").build());
}
}
然后在资源实现中抛出异常,客户端会收到一个漂亮的 json 格式的 http 错误正文。
@Path("/properties")
public class PropertyService {
...
@GET @Path("/{key}")
@Produces({"application/json;charset=UTF-8"})
public Property getProperty(@PathParam("key") String key) {
// 200=OK(json obj), 404=NotFound
Property bean = DBUtil.getProperty(key);
if (bean==null) throw new NotFoundException();
return bean;
}
...
}
- - - -
Content-Type: application/json
{"status":404,"message":"Resource not found","description":null}