在 REST / Java 中,如果我的对象为空,我应该返回什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26862500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In REST / Java, what should I return if my object is null?
提问by David Brossard
I have a simple POJO that I annotated with REST annotations as follows:
我有一个简单的 POJO,我用 REST 注释对其进行了注释,如下所示:
@GET
@Path("/domains/{domainid}")
@Override
public Domain getDomain(@PathParam("domainid") UUID domainID) throws Exception {
logger.info("Retrieving domain "+ domainID);
Domain d = null;
try {
d = MyClient.getDomains().get(domainID.toString());
logger.debug("Returning "+d.getName());
} catch (Exception e) {
logger.error("Could not retrieve domain", e);
}
return d;
}
Note that the log statement including d.getName() can actually throw an NPE which is then caught and logged. That's not pretty but it's also not the point here.
请注意,包含 d.getName() 的日志语句实际上可以抛出一个 NPE,然后捕获并记录该 NPE。这并不漂亮,但这也不是这里的重点。
Ultimately whether d has a value or not, I return it.
最终无论 d 是否有值,我都会返回它。
In the case of a null value, my client receives an HTTP 204 status code. This is what wget displays: HTTP request sent, awaiting response... 204 No Content
在空值的情况下,我的客户端会收到一个 HTTP 204 状态代码。这是 wget 显示的内容:HTTP request sent, awaiting response... 204 No Content
Oddly enough, my browsers don't budge an inch. They still display the previous page (I suppose it makes sense to stay put when no content is received). I would have expected a blank page.
奇怪的是,我的浏览器一点也不移动。他们仍然显示上一页(我认为在没有收到任何内容时保持原状是有意义的)。我会期望一个空白页。
Three questions:
三个问题:
- is HTTP 204 the right response to be returned?
- how can I control that via annotations? Via other configuration?
- what is the standard REST best practice regarding null objects?
- HTTP 204 是要返回的正确响应吗?
- 我如何通过注释来控制它?通过其他配置?
- 关于空对象的标准 REST 最佳实践是什么?
Thanks
谢谢
EDIT
编辑
There is a great question on the very same topic here: Is it correct to return 404 when a REST resource is not found?
这里有一个关于同一主题的好问题:当找不到 REST 资源时返回 404 是否正确?
回答by Paul Samsotha
If the request is trying to GET/locate/find a resource, and it can't be found, traditionally, we should send a 404 Not Found. For further discussion see here.
如果请求试图获取/定位/查找资源,但找不到,传统上,我们应该发送 404 Not Found。有关进一步讨论,请参见此处。
That being said, I generally like to have my resource methods return Response
, as it's easier to fine tune the response the way I want (a little - not much - more detail here). But seeing as how your method is overriding an interface contract (and returning a model object), JAX-RS gives us a nice hierarchy of exceptions that will get mapped to a particular response/status. The list can be seen here.
话虽这么说,我一般喜欢让我的资源方法返回Response
,因为它更容易微调的回应,我想要的方式(一点点-不多-更多的细节在这里)。但是看到您的方法如何覆盖接口契约(并返回模型对象),JAX-RS 为我们提供了一个很好的异常层次结构,这些异常将映射到特定的响应/状态。可以在此处查看列表。
So in your particular case, if the resource can't be found, you can throw a WebApplicationException(Response.Status.NOT_FOUND)
or a NotFoundException
, and the exception will be mapped to a 404 Not Found. Something like
因此,在您的特定情况下,如果找不到资源,您可以抛出 aWebApplicationException(Response.Status.NOT_FOUND)
或 a NotFoundException
,异常将映射到 404 Not Found。就像是
d = MyClient.getDomains().get(domainID.toString());
if (d == null) {
throw new NotFoundException(); // <-- JAX-RS 2.0
// or throw new WebApplicationException(Response.Status.NOT_FOUND);
// ^^ JAX-RS 1.x
}
The method will exit when the exception is thrown, and the client will receive a response with a 404 Not Found status.
抛出异常时该方法将退出,客户端将收到状态为 404 Not Found 的响应。
Related Q&As
相关问答
- How to catch 404 (NotFoundException) without being dependant on a JAX-RS implementation?
- Is it correct to return 404 when a REST resource is not found?
EDIT
编辑
In the first line I stated "If the request is trying to GET/locate/find a resource..", but really, this applies to almost all cases we are using URI templates, whether it is for a GET, POST, PUT, DELETE, whatever. Consider this example
在第一行我说“如果请求试图获取/定位/查找资源..”,但实际上,这适用于我们使用URI 模板的几乎所有情况,无论是用于 GET、POST、PUT,删除,随便。考虑这个例子
@PUT
@Path("/customers/{id}")
public Response updateCustomer(@PathParam("id") long id, Customer customer) {
...
}
Here is a method that allows the client to update a customer via a PUT. The client should know the complete URI to the resource before trying to update it. If the {id}
parameter (used for lookup) is not found say in a database, then the resource doesn't exist, and a 404 Not Found should also be returned to the client.
这是一种允许客户端通过 PUT 更新客户的方法。在尝试更新资源之前,客户端应该知道资源的完整 URI。如果{id}
在数据库中找不到该参数(用于查找),则该资源不存在,并且还应向客户端返回 404 Not Found。