【问题标题】:Send 404 instead of 405 which is empty WebApplicationException发送 404 而不是 405,它是空的 WebApplicationException
【发布时间】:2018-09-24 20:04:07
【问题描述】:

我有 dropwizard.io 应用程序,但 GET 请求有问题,我的资源如下所示:

@Path("/foobar")
public class FooBarResource
  (...)
  @GET
  @Path("/{id}")
  @UnitOfWork
  public Response getFooBar( @PathParam("id") Long id){
    return Response.status(200).entity(FooBarService.get(id)).build();
  }

  @DELETE
  @Path("/{id}")
  @UnitOfWork
  public Response getFooBar( @PathParam("id") Long id){
    return Response.status(200).entity(FooBarService.delete(id)).build();
  }

  @PUT
  @Path("/{id}")
  @UnitOfWork
  public Response getFooBar( @PathParam("id") Long id, FooBar fooBar){
    return Response.status(204).entity(FooBarService.update(id, fooBar)).build();
  }
}

当我发送GET localhost:port/appPath/foobar/ 时,我得到的是 405 而不是 404。我怎样才能得到 404?当我调试我的应用程序时,我只有一个javax.ws.rs.WebApplicationException,但它是空的。

【问题讨论】:

  • 还有哪些其他方法可以匹配 localhost:port/appPath/foobar/` 的 GET
  • 检查这是否有帮助:stackoverflow.com/questions/25040222/…
  • 不,在这种情况下,我的应用程序发送 405,我希望它发送 404。我可以映射一个异常,但里面充满了 null 值。
  • 删除getFooBar。再次发出GET 请求。怎么了? (顺便说一句:请再次确保您已在课堂上发布了所有相关的 JAX-RS 注释)
  • 我认为 405 符合预期。您只为 foobar/{id} 指定了 GET,而不为 foobar 指定了 GET。

标签: java rest http dropwizard


【解决方案1】:

您尝试 GET localhost:port/appPath/foobar/ 并得到 405(不允许的方法)。原因是这个资源 (=foobar) 存在,所以 404 (resource not found) 是错误的。如果你创建一个没有路径注释的 getFooBar() -> getFooBar2() 的副本,你应该得到 200。

如果您愿意,您可以创建一个容器过滤器,如果未准确找到路径,则该过滤器会抛出异常。然后可以将此异常映射到 404。

【讨论】:

    【解决方案2】:

    您应该使用可选的路径参数,如here 所述

    @GET
    @Path("/{id:.*}")
    @UnitOfWork
    public Response getFooBar( @PathParam("id") String id){
        try {
            return Response.status(200).entity(FooBarService.get(Long.parseLong(id))).build();
        } catch (NumberFormatException ignore) {
            return Response.status(404).build();
        }
    }
    

    【讨论】:

    • 还是405,app甚至没有进入getFooBar方法
    • 看起来很奇怪。如果您提供带有斜杠的请求,则应使用此方法捕获它。添加另一种带有 \@GET 和 \@UnitOfWork 注释但没有 \@Path 的方法,它应该处理直接 GET 请求。例如,请参阅Path docs
    猜你喜欢
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 2019-09-09
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多