避免進口傑克遜班,但只堅持純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}
謝謝jgm。抱歉。你如何編碼Jacson的ObjectMapper來從'ExceptionMapper' ???中的'ErrorInfo'對象創建JSON字符串。在此先感謝 – 2013-02-28 08:31:33
添加了一個完整的示例。 – jgm 2013-02-28 09:58:05
只有最後一個問題jgm。我在Jetty - Jersey環境中,並且我總是在exception.getMessage()中獲取null。我只想返回狀態描述。提前致謝。 – 2013-02-28 11:12:00