在REST / Java中,如果我的对象为null,我应该返回什么? [英] In REST / Java, what should I return if my object is null?

查看:243
本文介绍了在REST / Java中,如果我的对象为null,我应该返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的POJO,我用REST注释注释如下:

I have a simple POJO that I annotated with REST annotations as follows:

@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;
}

请注意,包含d.getName()的日志语句实际上可以抛出NPE然后捕获并记录。这不是很漂亮,但这也不是重点。

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是否有值,我将其退回。

Ultimately whether d has a value or not, I return it.

在空值的情况下,我的客户端收到HTTP 204状态代码。这是wget显示的内容:已发送HTTP请求,等待响应... 204无内容

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

奇怪的是,我的浏览器不会让步。它们仍然显示上一页(我认为在没有收到内容时保持放置是有意义的)。我本来期望一个空白页。

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.

三个问题:


  • 是HTTP 204返回正确的回复?

  • 如何通过注释控制?通过其他配置?

  • 关于空对象的标准REST最佳实践是什么?

谢谢

===编辑===

这里有一个很好的问题:< a href =https://stackoverflow.com/questions/26845631/is-it-correct-to-return-404-when-a-rest-resource-is-not-found/26845991#26845991>是否正确在找不到REST资源时返回404?

There is a great question on the very same topic here: Is it correct to return 404 when a REST resource is not found?

推荐答案

如果请求尝试获取/定位/找到一个资源,但是找不到它,传统上我们应该发送一个404 Not Found。有关请参阅此处的进一步讨论。

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.

话虽如此,我通常喜欢我的资源方法返回响应,因为它更容易按我想要的方式微调响应(一点点 - 不多 - 更多细节这里)。但是看看你的方法如何覆盖接口契约(并返回一个模型对象),JAX-RS为我们提供了一个很好的异常层次结构,它将被映射到特定的响应/状态。该列表可以在这里看到

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.

所以在您的特定如果无法找到资源,可以抛出 WebApplicationException(Response.Status.NOT_FOUND) NotFoundException ,异常将映射到404 Not Found。类似

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

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 
}

方法抛出异常时将退出,客户端将收到404 Not Found状态的响应。

The method will exit when the exception is thrown, and the client will receive a response with a 404 Not Found status.

相关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?

编辑

在第一行中,我说如果请求正在尝试获取/定位/查找资源..,但实际上,这几乎适用于我们使用的所有情况 URI模板,无论是GET,POST,PUT,DELETE等等。考虑这个例子

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

@PUT
@Path("/customers/{id}")
public Response updateCustomer(@PathParam("id") long id, Customer customer) {
    ...
}

这是一种允许客户通过PUT更新客户的方法。在尝试更新资源之前,客户端应该知道资源的完整URI。如果在数据库中找不到 {id} 参数(用于查找),则该资源不存在,并且还应返回404 Not Found客户。

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.

这篇关于在REST / Java中,如果我的对象为null,我应该返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆