Search code examples
haskellerror-code

Haskell - exit a program with a specified error code


In Haskell, is there a way to exit a program with a specified error code? The resources I've been reading typically point to the error function for exiting a program with an error, but it seems to always terminate the program with an error code of 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

Solution

  • Use exitWith from System.Exit:

    main = exitWith (ExitFailure 2)
    

    I would add some 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)