2012-04-06 2 views
5

나는 압축 할 수있는 파일을 읽기 위해이 코드를 썼다 : 그것은 잘 컴파일압축 해제 IOError를 잡는 방법은 무엇입니까?

import Codec.Compression.GZip 
import IO -- using IO.try 

read file = do 
    let f = L.readFile file 
    let c = fmap decompress $ f 

    unzipped <- try c 

    case unzipped of 
    Right b -> return b 
    Left _ -> f 

을하지만,이 압축 파일을 처리 할 수있는 유효한 방법이없는 것 같다. 압축 파일에 코드를 실행하면 좋은 작동하지만 압축되지 않은 파일은 예외와 함께 실패합니다이를 가능하게하는 방법에 대한

*** Exception: Codec.Compression.Zlib: incorrect header check 

어떤 생각을?

+0

는'IO.try'가되지 않습니다 (난 당신이 Data.ByteString.Lazy이 L. 자격을 가져온 가정) ... Control.Exception.That'은 어떨까요? http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Exception.html#v:try –

+2

요즘까지 'IO.try'는 특히 순수 코드에서 예외를 catch하지 않습니다. , 반면에'Control.Exception.try'는 않습니다. – dave4420

답변

4

Codec.Compression.Zlib.Internal을 가져와야합니다. 특히 “Low-level API to get explicit error reports”이라는 제목의 섹션에 유의하십시오.

당신은 (안된주의)이 같은 것을 사용하는 것이 좋습니다 :

import qualified Codec.Compression.Zlib.Internal as Z 
import Control.Arrow (right) 

decompressWithoutExceptions :: L.ByteString -> Either Z.DecompressError L.ByteString 
decompressWithoutExceptions = finalise 
          . Z.foldDecompressStream cons nil err 
          . Z.decompressWithErrors Z.gzipFormat Z.defaultDecompressParams 
    where err errorCode errorString = Left errorCode 
     nil = Right [] 
     cons chunk = right (chunk :) 
     finalise = right L.fromChunks 

+0

와우 ... 여기서 무슨 일이 일어 났는지 설명해 주시겠습니까? :) – fho

+0

신경 쓰지 마세요, 작동합니까?! (어떤 비트를 이해하지 못합니까? decompressWithErrors'와'foldDecompressStream' 등이 설명되어 있습니다 (아마도 내가 명확하게 설명하지 못했을까요?) – dave4420

+0

이 finalize 메소드는 어디서 발생 했습니까? 나는 hayoo를 통해 그것을 찾지 못했습니다. – fho

2

예외가 발생하는 경우 Nothing을 얻을 수있는 spoon을 볼 수 있습니다.