2012-04-06 9 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' अब मान्य नहीं है ... Control.Exception.try' के बारे में क्या? http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Exception.html#v:try –

+2

बिंदु पर और अधिक, 'IO.try' विशेष रूप से शुद्ध कोड से अपवाद नहीं पकड़ता है , जबकि '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 

(मुझे लगता है आप आयात किया है Data.ByteString.Lazy एल के रूप में योग्य)

+0

वाह ... क्या आप समझा सकते हैं कि यहां क्या हो रहा है? :) – fho

+0

इससे कोई फर्क नहीं पड़ता, क्या यह काम करता है ?! (जो बिट्स आप समझ में नहीं आते हैं? 'डिकंप्रेसविथइरर्स' और 'फोल्ड डिकंप्रेसस्ट्रीम' इत्यादि को मैंने प्रलेखन में समझाया है (शायद स्पष्ट रूप से पर्याप्त नहीं है?) – dave4420

+0

यह अंतिम विधि कहां से आती है? मुझे इसे हू के माध्यम से नहीं मिला। – fho

2

आप spoon पर देखना चाहते हैं, जो आपको अपवाद फेंकने पर Nothing प्राप्त करने की अनुमति देगा।