James Hamilton
James Hamilton

Reputation: 457

How do you print an error from a child thread in Haskell?

Given the following code:

module Main where

import Control.Concurrent

main :: IO ()
main = forkIO errorPrinter >> threadDelay 1000000 >> print "Finished"

errorPrinter = error "You can't see me!"

I would expect, that upon running this code I would see this:

"You can't see me"
"Finished!"

Printed to the console. However, "You can't see me" is never printed.

I realise that using error is not a good idea in production code, but I use it in development and I find that no errors are printed to the console - even those raised by dependencies.

I am sure this problem has an easy solution. I can't be the first person to have this issue, but I can't find an answer anywhere.

Any help would be much appreciated!

Upvotes: 4

Views: 448

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152867

I can't reproduce your problem; for me, it does print "You can't see me!":

% runhaskell test.hs
test.hs: You can't see me!
CallStack (from HasCallStack):
  error, called at test.hs:8:16 in main:Main
"Finished"

I see similar behavior as far back as GHC 7.6 (the oldest GHC I have lying around); I would be mildly surprised to learn that this behavior has changed significantly in the last twenty years or so.

Anyway I would recommend switching over to printing the message you want printed:

import System.IO
errorPrinter = hPutStrLn stderr "You can't see me!"

Say what you mean, and all that.

Upvotes: 1

Related Questions