ZIO 2: STDOUT and STDERR console output with foldZIO, success, failure

As a brief ZIO 2 example, the end of this Scala/ZIO source code shows how to print information to the console in a ZIO application, both in the success case (STDOUT) and also in the failure case (STDERR):

val program = for
    client: Client   <- ZIO.service[Client]
    res: Response    <- client.url(url).get("/")
    jsonBody: String <- res.body.asString
    data: Data       <- ZIO.fromEither(jsonBody.fromJson[Data])
yield
    data

val run =
    program.provide(
        Client.default,
        Scope.default
    ).foldZIO(
        failure => Console.printLineError(s"failure = $failure"),
        success => Console.printLine(s"success = $success")
    )

As shown, I do this with the foldZIO function, which lets me handle the failure and success cases as shown with these two Console functions:

  • Console.printLineError
  • Console.printLine

I’ll share more of this code as time goes on, but basically I’m using a ZIO HTTP Client along with ZIO JSON to retrieve some JSON data and then print it to the system console (command line). I’m doing this because I essentially want this to be a little script to retrieve some data for me periodically.