在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发布于 2017-06-17 21:15:50
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)发布于 2020-11-18 14:29:10
只允许出现错误消息的另一种方法是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)接受的答案允许设置退出错误代码,因此它更接近问题的确切表达方式。
https://stackoverflow.com/questions/44604701
复制相似问题