Handling Empty POST Response in Hippo CRISP

October 19th 2018 Hippo CMS Java

One could argue that a JSON REST service should never return an empty body, but you might not always have a say in how a service you need to call will behave. Unfortunately, CRISP API in Hippo CMS throws a NullPointerException if the response body is empty.

The approach to making a POST request in CRISP is not very discoverable but it is at least documented:

ResourceServiceBroker broker =
    HippoServiceRegistry.getService(ResourceServiceBroker.class);

ExchangeHint exchangeHint = ExchangeHintBuilder.create()
        .methodName("POST")
        .build();

broker.resolve(DEMO_RESOURCE, "/submit", exchangeHint);

When the service response body is empty, theresolve method will throw an exception:

org.onehippo.cms7.crisp.api.resource.ResourceException: Unknown error.

Not very informative, but we can see its cause being a NullPointerEception. It probably indicates a failed attempt at parsing the empty body.

Although the exception was thrown, the POST request succeeded and we could just quietly catch the exception and continue execution. This approach could hide real errors if we mistakenly caught other exceptions, therefore we'd like to avoid it if possible.

If we know that the body will always be empty or if we're simply never interested in it, then we can prevent the exception from being thrown by handling the response as binary:

ResourceServiceBroker broker =
    HippoServiceRegistry.getService(ResourceServiceBroker.class);

ExchangeHint exchangeHint = ExchangeHintBuilder.create()
        .methodName("POST")
        .build();

broker.resolveBinary(DEMO_RESOURCE, "/submit", exchangeHint);

The resolveBinary method doesn't fail if the response body is empty, so we can still treat any exceptions thrown as errors.

Get notified when a new blog post is published (usually every Friday):

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.
If you need a team of experienced software engineers to help you with a project, contact us at Razum.
Copyright
Creative Commons License