インポート 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}