mar*_*tin 5 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
Run Code Online (Sandbox Code Playgroud)
Zet*_*eta 11
使用exitWith来自System.Exit:
main = exitWith (ExitFailure 2)
Run Code Online (Sandbox Code Playgroud)
为方便起见,我会添加一些助手:
exitWithErrorMessage :: String -> ExitCode -> IO a
exitWithErrorMessage str e = hPutStrLn stderr str >> exitWith e
exitResourceMissing :: IO a
exitResourceMissing = exitWithErrorMessage "Resource missing" (ExitFailure 2)
Run Code Online (Sandbox Code Playgroud)
仅允许错误消息的替代方法是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)
Run Code Online (Sandbox Code Playgroud)
不过,接受的答案允许设置退出错误代码,因此它更接近问题的确切措辞。
| 归档时间: |
|
| 查看次数: |
550 次 |
| 最近记录: |