Freer-Simple Freer Monads如何使用错误效果统一IO异常处理

时间:2018-09-01 11:59:17

标签: haskell free-monad

我正在使用freer-simple编写超简单的DSL。它所做的只是读取一个文件。 我有一个关于文件名的规则,它们不能包含字母x。任何打开带有字母x的文件的尝试都将导致:左(AppError "No Xs allowed in file name")

fileSystemIOInterpreter中读取文件并将其作为应用程序错误抛出时,如何捕获IO错误?就是我正在尝试将选定的IO异常转换为AppErrors(请参见??????)。

{- File System Lang -}

data FileSystem r where
  ReadFile :: Path a File -> FileSystem StrictReadResult

readFile :: Members '[FileSystem, Error AppError] effs => Path a File -> Eff effs StrictReadResult
readFile path = let
                  pthStr = toStr $ toFilePath path
                in
                  F.elem 'x' pthStr
                        ? throwError (AppError "No Xs allowed in file name")
                        $ send $ ReadFile path

{- Errors -}

newtype AppError = AppError String deriving Show

runAppError :: Eff (Error AppError ': r) a -> Eff r (Either AppError a)
runAppError = runError

{- File System IO Interpreter -}

fileSystemIOInterpreter :: forall effs a. (Members '[Error AppError] effs, LastMember IO effs) => Eff (FileSystem ': effs) a -> Eff effs a
fileSystemIOInterpreter = interpretM $ \case
                                          ReadFile path -> F.readFileUTF8 path
                                          -- ??????

-- this compiles: fileSystemIOInterpreter effs = throwError $ AppError "BLahh"

application :: Members '[FileSystem, Error AppError] effs => Path a File -> Eff effs StrictReadResult
application = readFile

ioApp :: Path a File -> IO (Either AppError StrictReadResult)
ioApp path = runM
              $ runAppError
              $ fileSystemIOInterpreter
              $ application path

-- running the app

demoPassApp = ioApp [absfile|C:\Vids\SystemDesign\VidList.md|]
>> Right (Right "Text content of VidList.md")

demoFailApp = ioApp [absfile|C:\Vids\SystemDesign\VidList.txt|]
>> Left (AppError "No Xs allowed in file name")

demoFailIOApp = ioApp [absfile|C:\Vids\SystemDesign\MissingFile.md|]
>> *** Exception: C:\Vids\SystemDesign\MissingFile.md: openBinaryFile: does not exist (No such file or directory)
-- I want to turn this into an AppError

2 个答案:

答案 0 :(得分:3)

interpretMIO中带了一个口译员(此处是its first argument has type eff ~> mm ~ IO),所以不允许您通过{抛出AppError {1}}约束。

您可以使用Members '[Error AppError] effs,并拥有对interpret的完全访问权限。大致如下:

effs

答案 1 :(得分:1)

这是一个完整的工作示例:

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

import Data.String
import qualified Data.ByteString.Char8 as B
import Control.Exception
import Data.List
import Data.Text (Text, pack, unpack)
import Data.Text.IO
import Data.Text.Encoding (decodeUtf8)
import Control.Natural (type (~>))
import qualified  Control.Monad.Freer.Error as ER
import Control.Monad.Freer
  (
    Eff
  , LastMember
  , Member
  , Members
  , interpret
  , send
  , sendM
  , runM
  )

readFileUTF8 :: String -> IO Text
readFileUTF8 path = decodeUtf8 <$> B.readFile path

ioToAppErr :: IOException -> AppError
ioToAppErr ioe = AppError (displayException ioe)

newtype AppError = AppError String deriving Show

data FileSystem r where
  ReadFile :: FilePath -> FileSystem Text

readFile :: Members '[FileSystem, ER.Error AppError] effs => FilePath -> Eff effs Text
readFile fpath = if (elem 'x' fpath)
                     then (ER.throwError  (AppError "No Xs allowed in file name"))
                 else(send $ ReadFile fpath)

runAppError :: Eff (ER.Error AppError ': r) a -> Eff r (Either AppError a)
runAppError = ER.runError

fileSystemIOInterpreter
  :: (Members '[ER.Error AppError] effs, LastMember IO effs)
  => Eff (FileSystem ': effs) a -> Eff effs a
fileSystemIOInterpreter = interpret $ \case
    ReadFile path -> do
        r <- sendM (try (readFileUTF8 path))
        case r of
            Left (e :: IOException) -> ER.throwError (ioToAppErr e)
            Right f -> pure f

application :: Members '[FileSystem, ER.Error AppError] effs => FilePath -> Eff effs Text
application = Main.readFile

ioApp :: FilePath -> IO (Either AppError Text)
ioApp path = runM
              $ runAppError
              $ fileSystemIOInterpreter
              $ application path

main :: IO ()
main = do
  let pathX = "C:\\text.info"
  let pathNoX = "C:\\simple.t"
  let pathNoSuchAFile = "C:\\habrahabr.bib"
  result <- ioApp pathX
  Data.Text.IO.putStrLn $ pack (show result)

依赖项:

  • 基本> = 4.7 && <5
  • 文本
  • 更简单
  • 自然转变
  • 字节串