simonalexander2005
simonalexander2005

Reputation: 4577

Missing body in negative REST responses

I have created my own REST classes, and am calling the using curl -v "http://10.0.0.4:49152/rest/geo?loc=12345&get=description" (for example). I also call them from java using httpClient.send.

In both cases, if the REST class returns a string then everything is fine - the message body contains the String; but if my REST class instead throws an exception, the returned object/message doesn't contain my custom 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;
    }
}

The response is a code 400, which is what I'd expect, but this is my output:

*   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

Likewise in the java HttpResponse message I can see the code (400) but not the message in my Exception.

How can I see the returned message?

Upvotes: 1

Views: 113

Answers (1)

andbi
andbi

Reputation: 4454

This is probably a container-specific issue. To solve such problems once and for all, I personally make use of ExceptionMapper like this:

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();
    }
}

Annotated with the @Provider annotation, the class will be automatically discovered by the container.

Upvotes: 1

Related Questions