Haskell - 退出带有指定错误代码的程序

时间:2017-06-17 12:33:11

标签: haskell error-code

在Haskell中,有没有办法退出带有指定错误代码的程序?我一直在阅读的资源通常指向error函数,用于退出程序时出错,但它似乎总是终止程序,错误代码为1

[martin@localhost Haskell]$ cat error.hs
main = do
    error "My English language error message"
[martin@localhost Haskell]$ ghc error.hs
[1 of 1] Compiling Main             ( error.hs, error.o )
Linking error ...
[martin@localhost Haskell]$ ./error 
error: My English language error message
[martin@localhost Haskell]$ echo $?
1

2 个答案:

答案 0 :(得分:10)

使用exitWith中的System.Exit

main = exitWith (ExitFailure 2)

为方便起见,我会添加一些助手:

exitWithErrorMessage :: String -> ExitCode -> IO a
exitWithErrorMessage str e = hPutStrLn stderr str >> exitWith e

exitResourceMissing :: IO a
exitResourceMissing = exitWithErrorMessage "Resource missing" (ExitFailure 2)

答案 1 :(得分:1)

仅允许显示错误消息的替代方法是die

import System.Exit

tests = ... -- some value from the program
testsResult = ... -- Bool value overall status

main :: IO ()
main = do
    if testsResult then
        print "Tests passed"
    else
        die (show tests)

尽管接受的答案允许设置退出错误代码,所以它更接近问题的确切措辞。

相关问题