Haskell - exit program with specified error code

In Haskell, is there a way to exit the program with the specified error code? The resources I've read usually point to a function error

to exit a program with an error, but it always exits with an error code 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

      

+3


source to share


1 answer


Use exitWith

from System.Exit

:

main = exitWith (ExitFailure 2)

      



I would add a few helpers for convenience:

exitWithErrorMessage :: String -> ExitCode -> IO a
exitWithErrorMessage str e = hPutStrLn stderr str >> exitWith e

exitResourceMissing :: IO a
exitResourceMissing = exitWithErrorMessage "Resource missing" (ExitFailure 2)

      

+9


source







All Articles