2017-06-17 86 views
3

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

[[email protected] Haskell]$ cat error.hs 
main = do 
    error "My English language error message" 
[[email protected] Haskell]$ ghc error.hs 
[1 of 1] Compiling Main    (error.hs, error.o) 
Linking error ... 
[[email protected] Haskell]$ ./error 
error: My English language error message 
[[email protected] Haskell]$ echo $? 
1 
System.Exit
+4

也许你这时应该使用['System.Exit'(https://开头hackage.haskell.org/package/base-4.9.1.0/docs/System-Exit.html)。 –

+0

@WillemVanOnsem我认为这就是我正在寻找的。谢谢。 – martin

回答

9

使用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)