Haskell 如何捕获解压缩IOR错误?

Haskell 如何捕获解压缩IOR错误?,haskell,gzip,Haskell,Gzip,我编写此代码段是为了读取可能被压缩的文件: 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 关于如何实现这一

我编写此代码段是为了读取可能被压缩的文件:

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

关于如何实现这一点有什么想法吗?

您可能想看看,如果引发异常,这将允许您什么也得不到。

您需要导入Codec.Compression.Zlib.Internal。请特别注意标题为的部分

您将希望使用以下内容(注意:未测试):


(我猜您已经导入了Data.ByteString.Lazy,限定为L。)

IO.try
不推荐使用。。。那么Control.Exception呢?试试`?更重要的是,
IO.try
特别不捕获纯代码中的异常,而
Control.Exception.try
捕获纯代码中的异常。没关系,它能工作吗?!(我链接到的文档中解释了哪些位您不理解?
解压错误
折叠压缩流
,等等(可能不够清楚。)这个最终确定方法来自哪里?我没有通过hayoo找到它。
finalize
在最后一行中定义。其目的是将结果从类型
或Z.DecompressError[Data.ByteString.ByteString]
转换为
或Z.DecompressError L.ByteString
(即将“success”类型从严格的ByteString列表转换为单个惰性的ByteString)。
*** Exception: Codec.Compression.Zlib: incorrect header check
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