将消息错误添加到 Jersey 中的响应正文

Add message error to response body in Jersey

我有这个端点:

    @POST
    @Path("login")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response doLogin(LoginCredentials loginCredentials) {
        try {
            usersService.validate(loginCredentials);
            return Response.ok().build();
        } catch (InvalidCredentialsException e) {
            return Response.status(Response.Status.UNAUTHORIZED).build();
        } catch (NotAuthorizedUserException e) {
            return Response.status(Response.Status.UNAUTHORIZED).build();
        }
    }

UNAUTHORIZED的情况下,我想发送一条消息来指定具体的错误。怎么做到的?

如果响应是 ok,我会这样做:

return Response.ok("Some message here").build();

使用实体(对象数据)方法:

Response.status(Response.Status.UNAUTHORIZED).entity("Some message here").build();