Java Jersey PathParams 检查和 NotFoundException 自定义消息

Java Jersey PathParams Checking and NotFoundException custom message

我正在使用 Jersey 进行休息 API,JerseyTests 进行单元测试。

我一直在遵循 Internet 上似乎是 PathParams 检查和异常处理的常规做法,但我不太明白我在这里做错了什么:

RoomApplicationResource.java

@Path("demandes")
public class RoomApplicationResource {
    @GET
    @Path("/{email}/{requestNumber}")
    public Response getRoomApplication(
            @PathParam("email") String email, 
            @PathParam("requestNumber") String requestNumber) throws NoRoomApplicationFoundException {

        if (email == "wrong@email.com" || requestNumber == "wrong") {
            throw new NoRoomApplicationFoundException("bad request");
        }

        String response =requestNumber+" is valid for "+email;

        return  Response.ok(response).build();
    }
}

我这样处理异常:

NotFoundMapper.java

@Provider
public class NotFoundMapper implements ExceptionMapper<NoRoomApplicationFoundException>{

    @Override
    public Response toResponse(NoRoomApplicationFoundException e) {
        return Response.status(Response.Status.NOT_FOUND)
                .entity(e.getMessage()).build();
    }
}

NoRoomApplicationFoundException.java

public class NoRoomApplicationFoundException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public NoRoomApplicationFoundException() {
        super();
    }

    public NoRoomApplicationFoundException(String msg) {
        super(msg);
    }

    public NoRoomApplicationFoundException(String msg, Exception e) {
        super(msg, e);
    }
}

我是这样测试的:

RoomApplicationResourceTest.java

public class RoomApplicationResourceTest extends JerseyTest {

    @Override
    protected Application configure() {
        return new ResourceConfig(RoomApplicationResource.class, NotFoundMapper.class);
    }

    // This test works fine as expected
    @Test
    public void whenParametersAreExistantReturnTheOkResponse() {
        final Response res = target("demandes").path("valid@email.com").path("12345").request().get();

        assertEquals(200, res.getStatus());
        assertEquals("12345 is valid for valid@email.com", res.readEntity(String.class));
    }

    // This does not work as expected
    @Test
    public void whenEmailParameterDoNotMatchToAnyRoomApplicationThenReturns404() {
        final Response res = target("demandes").path("wrong@email.com").path("12345").request().get();

         assertEquals(404, res.getStatus());
         assertEquals("bad request", res.readEntity(String.class));
    }

}

问题1:这种对params进行条件检查的方式是不是错了?电子邮件无效的第二次测试的结果应该抛出我的自定义异常和 return 404,而不是 returns 200 和有效消息。

问题2:在这种情况下,我应该如何处理缺少的参数?泽西岛似乎默认抛出 NotFoundException 。有没有一种简单的方法来自定义该错误的消息,或者可能使用我的自定义异常,因为我的资源方法末尾的抛出 NoRoomApplicationFoundException 似乎没有做任何事情?

提前致谢。亚历克斯

问题一

是的。问题是您使用 == 来比较字符串。您应该改为使用 String.equals()。参见 How do I compare Strings in Java?

if ("wrong@email.com".equals(email) || "wrong".equals(requestNumber)) {
    throw new NoRoomApplicationFoundException("bad request");
}

问题二:

这个问题好像和你的第一个问题有关。但对我来说,作为一般规则(这只是我),如果我正在编写异常 class 并且该异常特定于我的 JAX-RS 应用程序(这意味着我将在 JAX- RS 应用程序),我只会使异常扩展 WebApplicationException。默认情况下会处理此异常,您可以在 class 中创建 Response。不需要任何 ExceptionMapper。例如

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

public class NoRoomApplicationFoundException extends WebApplicationException {

    private static final long serialVersionUID = 1L;

    public NoRoomApplicationFoundException() {
        this("Room not found", 400);
    }

    public NoRoomApplicationFoundException(String msg, int status) {
        this(Response.status(status).entity(msg).build());
    }

    public NoRoomApplicationFoundException(Response response) {
        super(response);
    }
}

您可以完全摆脱 NotFoundMapper,这会很好。

if ("wrong@email.com".equals(email) || "wrong".equals(requestNumber)) {
    throw new NoRoomApplicationFoundException();
}

一些资源: