HTTP response validation with the Vert.x Web Client
By default, a Vert.x Web Client request ends with an error only if something wrong happens at the network level.
In other words, a 404 Not Found response, or a response with the wrong content type, are not considered as failures.
Hence, you would usually perform sanity checks manually after the response is received:
Starting with Vert.x 3.6, you can can trade flexibility for clarity and conciseness using response predicates.
Response predicates
Response predicates can fail a request when the response does not match criterion.
The Web Client module comes with a set of ready-to-use predicates:
The web is full of HTTP/JSON endpoints, so there is no doubt the ResponsePredicate.SC_SUCCESS and ResponsePredicate.JSON can be handy.
Nevertheless, you might also need to check that the status code is whithin a specific range:
Eventually, predicates were not designed for status code and content type checking only, so feel free to create your own validation code:
Note that response predicates are evaluated before the response body is received.
Therefore you can’t inspect the response body in a predicate test function, only status code, status message and response headers.
Dealing with failures
By default, response predicates (including the predefined ones) use a generic error converter which discards the response body and conveys a simple message.
You can customize the exception class by changing the error converter:
Beware that creating exceptions in Java comes with the performance cost of capturing the call stack.
The generic error converter generates exceptions that do not capture it.
Reading details in error responses
Many web APIs provide details in error responses.
For example, the Marvel API uses this JSON object format:
To avoid losing this information, it is possible to wait for the response body to be fully received before the error converter is called:
That’s it! Feel free to comment here or ask questions on our community channels.