我正在为我的RESTful Web服务创建一个客户端。在这种情况下,expected并不总是返回预期的对象(例如,在给定参数上找不到任何东西,因此返回为NULL)。
@GET
@Path("/person/{name}")
@Produces("application/xml")
public Person getPerson(@PathParam("name") String name) {
return people.byName(name);
}
如果找不到给定的名称,byName()方法将返回NULL。在解组给定对象时,这将引发异常。什么是最常见和最干净的方式,才能只产生if/else语句或其他以不同方式处理返回的方法?
JAXBContext jcUnmarshaller = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jcUnmarshaller.createUnmarshaller();
return (Person) unmarshaller.unmarshal(connection.getInputStream());
溶液
getPerson( ) throws WebApplicationException {
throw new WebApplicationException(404);
}
发布于 2012-06-05 18:44:37
处理这种情况的惯用方法是返回404未找到的响应代码。使用贾克斯,您可以抛出WebApplicationException
@GET
@Path("/person/{name}")
@Produces("application/xml")
public Person getPerson(@PathParam("name") String name) {
Person personOrNull = people.byName(name);
if(personOrNull == null) {
throw new WebApplicationException(404);
}
return personOrNull;
}
发布于 2012-06-05 18:38:33
如果您正在寻找纯REST服务,则应该返回HTTP响应代码404 --在找不到人时不返回。所以,它看起来是这样的:
public Person getPerson(@PathParam("name") String name) {
Person person = people.byName(name);
if (null != person) {
return person
}
else {
//return 404 response code (not sure how to do that with what you're using)
}
}
https://stackoverflow.com/questions/10902711
复制相似问题