eclipse-vertx / vert.x

Vert.x is a tool-kit for building reactive applications on the JVM
http://vertx.io
Other
14.26k stars 2.07k forks source link

Future expectation 4.x #5197

Closed vietj closed 4 months ago

vietj commented 4 months ago

Future control flow using predicates.

Future has already synchronous operations modifying the control flow

This contribution aims to transform a success into a failure based on the result of a predicate.

Goals

Vert.x Web Client has something close to this with HTTP expectations:

    client
      .get(8080, "myserver.mycompany.com", "/some-uri")
      .expect(ResponsePredicate.SC_SUCCESS)
      .expect(ResponsePredicate.JSON)
      .send()
      .onSuccess(res -> {
        // Safely decode the body as a json object
        JsonObject body = res.bodyAsJsonObject();
        System.out.println(
          "Received response with status code" +
            res.statusCode() +
            " with body " +
            body);
      })
      .onFailure(err ->
        System.out.println("Something went wrong " + err.getMessage()));

A predicate like interface Expectation: a synchronous predicate that checks a boolean value and has a method to create a meaningful exception.

Future<Buffer> body = client.request(options)
  .compose(req -> req
    .send()
    .expecting(resp -> resp.statusCode() == 200)
    .compose(resp -> resp.body()); 

The HTTP response status code can be captured so it can be reused.

Future<Buffer> body = client.request(options)
  .compose(req -> req
    .send()
    .expecting(HttpResponseExpectation.SC_OK)
    .compose(resp -> resp.body());