负 REST 响应中缺少正文

Missing body in negative REST responses

我已经创建了自己的 REST classes,并且正在调用 using curl -v "http://10.0.0.4:49152/rest/geo?loc=12345&get=description"(例如)。我还使用 httpClient.send.

从 java 调用它们

在这两种情况下,如果 REST class returns 一个字符串那么一切都很好——消息正文包含该字符串;但是如果我的 REST class 反而抛出异常,则返回的 object/message 不包含我的自定义消息:

@GET 
@Produces("text/plain")
@Override
public String get(@Context UriInfo uriInfo, @Context Request request)
{
    String queryString = uriInfo.getRequestUri().getQuery();
    //etc
    if (somethingIsWrong)
    {
        // I don't see this message in the response
        throw new BadRequestException("GET request issue - something is wrong");
    }
    else
    {
        return correctString;
    }
}

响应是代码 400,这是我所期望的,但这是我的输出:

*   Trying 10.0.0.4...
* TCP_NODELAY set
* Connected to 10.0.0.4 (10.0.0.4) port 49152 (#0)
> GET /rest/geo?loc=12345&get=description HTTP/1.1
> Host: 10.0.0.4:49152
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 400 Bad Request
< Date: Thu, 22 Oct 2020 14:20:37 GMT
< Content-length: 0
<
* Connection #0 to host 10.0.0.4 left intact

同样在 java HttpResponse 消息中,我可以看到代码 (400),但在我的异常中看不到消息。

如何查看返回的消息?

这可能是一个 container-specific 问题。为了一劳永逸地解决这些问题,我个人是这样使用ExceptionMapper的:

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class RestExceptionMapper implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable t) {
        Object entity;
        Response.Status status;
        if (t instanceof SomeException) {
            status = // compute status
            entity = t.getMessage();
        } else {
            status = Response.Status.INTERNAL_SERVER_ERROR;
            entity = "Server error";
        }

        return Response
                .status(status)
                .type(MediaType.TEXT_PLAIN)
                .entity(entity)
                .build();
    }
}

使用@Provider注解,class会被容器自动发现