I'm building a Rest Client
using jersey-client 2.19
:
public ReleaseEntity createRelease(ReleaseEntity newRelease, int workspaceId) {
Releases wrapper = new Releases();
wrapper.setData(Arrays.asList(newRelease));
WebTarget target = client.target(urlPrefix)
.path(AgmUrls.getReleasesUrl(workspaceId));
wrapper = target
.request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.entity(wrapper, MediaType.APPLICATION_JSON))
.readEntity(Releases.class);
return wrapper.getData().get(0);
}
The client is initialized in the constructor
this.client = ClientBuilder.newClient();
The problem is that, in case of bad response the post
call does not throw an exception, neither explicit
nor runtime
.
Should I do this manually, or am I missing something?
The framework should not throw an exception. The user should handle the response however they see fit. This is the same with any client. The Response
object will contain all the context you need to handle the response however you see fit.
So what you should do is get the Response
first
Response response = target
.request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.entity(wrapper, MediaType.APPLICATION_JSON));
Then you can check the status
int status = response.getStatus();
Then handle the status
if (status == 200) {
wrapper = response.readEntity(Releases.class);
...
} else {
handleOtherStatus();
}
If you do not get the Response
first, then you have no idea what the actual problem is, as readEntity(...)
will fail (as there it's not the body you are expecting), and throw a different exception. With the Response
at least you have some context if you want to tell the user what actual problem is.