Haskell - 退出带有指定错误代码的程序
Haskell - exit a program with a specified 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
使用exitWith
from 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)
另一种只允许错误消息的方法是 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)
接受的答案允许设置退出错误代码,因此它更接近问题的确切措辞。
在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
使用exitWith
from 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)
另一种只允许错误消息的方法是 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)
接受的答案允许设置退出错误代码,因此它更接近问题的确切措辞。