【问题标题】:Haskell - exit a program with a specified error codeHaskell - 以指定的错误代码退出程序
【发布时间】:2017-11-20 03:26:23
【问题描述】:

在 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
  • @WillemVanOnsem 我想这就是我想要的。谢谢。

标签: haskell error-code


【解决方案1】:

使用来自System.ExitexitWith

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)

【讨论】:

    【解决方案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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 2014-07-29
      • 2017-11-14
      • 2014-04-25
      • 1970-01-01
      相关资源
      最近更新 更多