如何在cats-effect的资源中添加适当的错误处理 [英] How to add proper error handling to cats-effect's Resource

查看:40
本文介绍了如何在cats-effect的资源中添加适当的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 cats-effect以纯粹的功能方式获取一些基本文件IO(写入/读取).遵循教程之后,下面就是我读取文件的结果:

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)
  }

现在在 handleErrorWith 函数中,我可以记录发生的任何错误,但是如何向其添加适当的错误处理(例如,返回 Resource [IO,Either [CouldNotReadFileError,BufferedReader]]])?

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]])?

推荐答案

可以通过对返回的IO值使用 .attempt 来添加正确的错误处理:

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

如果要将其添加到自己的ADT中,可以使用 leftMap :

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))

此外,您可能会对 ZIO 数据类型感兴趣具有受支持的cats效果实例,并且其形状略有不同形式为 IO [E,A] ,其中 E 捕获错误影响类型.

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.

这篇关于如何在cats-effect的资源中添加适当的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆