Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add proper error handling to cats-effect's Resource

I am trying to get some basic file IO (write/read) in a purely functional way using cats-effect. After following this tutorial, here is what I ended up with for reading a file:

private def readFile(): IO[String] = for {
  lines <-  bufferedReader(new File(filePath)).use(readAllLines)
} yield lines.mkString

def bufferedReader(f: File): Resource[IO, BufferedReader] =
  Resource.make {
    IO(new BufferedReader(new FileReader(f)))
  } { fileReader =>
    IO(fileReader.close()).handleErrorWith(_ => IO.unit)
  }

Now in the handleErrorWith function I could log any error occuring, but how can I add proper error handling to this (e.g. return a Resource[IO, Either[CouldNotReadFileError, BufferedReader]])?

like image 845
Florian Baierl Avatar asked Feb 06 '19 07:02

Florian Baierl


People also ask

How do you catch exceptions in Scala?

The try/catch construct is different in Scala than in Java, try/catch in Scala is an expression. The exception in Scala and that results in a value can be pattern matched in the catch block instead of providing a separate catch clause for each different exception. Because try/catch in Scala is an expression.

What is cats in Scala?

Cats is a library which provides abstractions for functional programming in the Scala programming language. Scala supports both object-oriented and functional programming, and this is reflected in the hybrid approach of the standard library.

What is try in Scala?

The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala. util. Either type. Instances of Try[T] , are either an instance of scala.


1 Answers

Proper error handling can be added via the use of .attempt on the returned IO value:

import scala.collection.JavaConverters._

val resourceOrError: IO[Either[Throwable, String]] = bufferedReader(new File(""))
  .use(resource => IO(resource.lines().iterator().asScala.mkString))
  .attempt

If you want to lift that into your own ADT, you can use leftMap:

import cats.syntax.either._

final case class CouldNotReadError(e: Throwable)

val resourceOrError: IO[Either[CouldNotReadError, String]] =
  bufferedReader(new File(""))
    .use(resource => IO(resource.lines().iterator().asScala.mkString))
    .attempt
    .map(_.leftMap(CouldNotReadError))

Additionally, you might be interested in the ZIO datatype, which has supported cats-effect instances, and has a slightly different shape of the form IO[E, A] where E captures the error effect type.

like image 129
Yuval Itzchakov Avatar answered Oct 11 '22 21:10

Yuval Itzchakov