Haskell错误处理,记录控制台的无效文件路径

时间:2017-08-22 20:24:13

标签: haskell error-handling console

作为this project的一部分,我想验证提供密码的文件的路径,即pwds <- case cfgPasswords of Just passPath -> (map (Just . T.unpack) . lines) <$> readFileUtf8 passPath,如果文件的路径无效我会喜欢将消息记录到控制台。

如何在Haskell中实现这一目标?

logf' "Log level is {}" [show logLevel]
setLogLevel logLevel
debugf' "Configuration: {}" [show cfg]
ncpus <- getNumProcessors
logf' "Utilizing {} core(s)" [ncpus]
setNumCapabilities ncpus
pwds <- case cfgPasswords of
    Just passPath -> (map (Just . T.unpack) . lines) <$>
        readFileUtf8 passPath
    Nothing       -> return $ replicate (length cfgPublicKeys) Nothing
when (length cfgPublicKeys /= length cfgPrivateKeys) $
    errorL' "The same amount of public keys and private keys must be specified"
when (length cfgPublicKeys /= length pwds) $
    errorL' "The same amount of passwords must be included in the passwords file as the number of private keys. (If a private key has no password, include a blank line.)"
when (cfgPort == 0) $
    errorL' "A listening port must be specified with 'port' in the configuration file or --port at runtime"

这个想法是它会在when (length cfgPublicKeys /= length cfgPrivateKeys) $之上。

2 个答案:

答案 0 :(得分:3)

我不确定您在此代码段中是否有足够的信息可以让某人通过您输入签名来精确推断出这里发生了什么。

您链接的项目似乎是用go?

编写的

您的代码示例中似乎有许多项目特定的功能。

对于“此文件路径是否指向文件”的情况,您可以执行以下操作:

checkForAFile :: FilePath -> IO ()
checkForAFile path = do
    validFile <- doesFileExist path
    if validFile
       then putStrLn $ path ++ " is a file that exists"
       else putStrLn $ path ++ " is not a file that exists"

doesFileExistSystem.Directory库中可用的函数,是回答文件路径是否指向文件的问题的规范方法。

不知道这段代码是做什么的,我不能建议一个合适的位置来支票,但希望这足以让你继续。

如果不是这样的话,我可能会建议您尝试使用一些较少的Haskell代码。

答案 1 :(得分:1)

在链接的gist中,您有以下函数导致语法错误:

checkForAFile :: FilePath -> IO ()
checkForAFile path
    validFile <- doesFileExist filePath
    if validFile
       then putStrLn $ filePath ++ " is a file that exists"
       else putStrLn $ filePath ++ " is not a file that exists"

那是因为你忘了=号。请改用:

checkForAFile :: FilePath -> IO ()
checkForAFile path = do
    validFile <- doesFileExist filePath
    if validFile
       then putStrLn $ filePath ++ " is a file that exists"
       else putStrLn $ filePath ++ " is not a file that exists"