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



在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

使用 System.Exit 中的exitWith

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)

仅允许错误消息的替代方法是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)

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

相关内容

最新更新