2014-12-18 3 views
6

일부 스카치 스트림 문서의 예제를 살펴 보겠습니다. scalaz-streams의 태스크에서 예외 로깅 및 무시

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입니다.

+0

을하지 단계를 반복합니다. scalaz 함께 할 수 있지만, 실패한 매핑 및 경우에'Try'을 사용하여 오류를 방법을 기록 할 수 있습니다 당신은 (아마 이런 식으로 : https://github.com/scalaz/scalaz-stream/blob/master/src/test/scala/scalaz/stream/examples/WritingAndLogging.scala#L63). –

답변

3

당신은 \/추가 처리는 아마 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 
+0

그렇다면 실행/시도 실행 프로그램이나 특정 예외에 대해 작동하도록 지정할 수있는 제네릭 처리기가 없습니다. 또한,이 경우에는'.map (collectCome)'이'.collect (collectSome)'이어야한다고 생각합니다. – kareblak

+0

기본적으로 프로세스는 첫 번째 예외에서 실패하지만 모든 로그를 기록한다는 사실을 알고 있으므로 실패 할 수있는 각 단계에서 예외를 잡아야합니다. 예, 오타입니다. 수집해야합니다 (collectSome) –

+0

예, 읽기에 매우 편리합니다. 특히 데이터 읽기 및 품질에 대한 제어 권한이없는 경우에는 scalaz-streams이 만들어졌습니다. 자료. 스트림입니다. 어떤 경우에는 손상된 물건을 버리고 싶을뿐입니다. 하지만 그 대답은 실제로 다루고 있습니다. – kareblak