gpt4 book ai didi

scala - 在 scalaz-streams 中记录和忽略来自 Task 的异常

转载 作者:行者123 更新时间:2023-12-04 15:33:39 25 4
gpt4 key购买 nike

让我们从一些 scalaz-stream 文档中举一个例子,但有一个理论扭曲。

import scalaz.stream._
import scalaz.concurrent.Task

val converter: Task[Unit] =
io.linesR("testdata/fahrenheit.txt")
.filter(s => !s.trim.isEmpty && !s.startsWith("//"))
.map(line => fahrenheitToCelsius(line.toDouble).toString)
.intersperse("\n")
.pipe(text.utf8Encode)
.to(io.fileChunkW("testdata/celsius.txt"))
.run

// at the end of the universe...
val u: Unit = converter.run

在这种情况下,文件很可能包含一些非双字符串,而 fahrenheitToCelsius会扔一些 NumberFormatException .假设在这种情况下,我们可能希望记录此错误并忽略它以进行进一步的流处理。这样做的惯用方法是什么?我看过一些例子,但他们通常 collectFrom流。

最佳答案

您可以使用 scalaz.\/和其他处理步骤来完成

  def fahrenheitToCelsius(line: String): Throwable \/ String = 
\/.fromTryCatchNonFatal {
val fahrenheit = line.toDouble
val celsius = fahrenheit // replace with real convert
celsius.toString
}

def collectSome[T]: PartialFunction[Option[T], T] = {
case Some(v) => v
}

def logThrowable[T]: PartialFunction[Throwable \/ T, Option[T]] = {
case -\/(err) =>
err.printStackTrace()
None
case \/-(v) => Some(v)
}

val converter: Task[Unit] =
io.linesR("testdata/fahrenheit.txt")
.filter(s => !s.trim.isEmpty && !s.startsWith("//"))
.map(fahrenheitToCelsius)
.map(logThrowable)
.collect(collectSome)
.intersperse("\n")
.pipe(text.utf8Encode)
.to(io.fileChunkW("testdata/celsius.txt"))
.run

关于scala - 在 scalaz-streams 中记录和忽略来自 Task 的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27549825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com