Question

Hello I need to write function than will send and receive messages over tcp and auto reconnect if connection is broken. Messages is taken from STM Channel

f ch a b = 
    h <- connectTo a b
    forever $ do
        c <- atomically $ readTChan ch
        {- do smth with c -}
    `catch` (const $ f ch a b)

My problem is that if connection is broken I'll lost 'c' that I've read from channel. So in catch clause I want to no something like unGetTChan but in this code 'c' is not in catch. Can you advise ''haskellic'' way to do such a thing?

update after FUZxxl's message

After FUZxxl's comment I've rewritten function into next form

fun ch a b = do
h <- connectTo a b
forever $ do
    c <- atomically $ readTChan chan
    do   
        {- do smth with c -}
        `catch` (const $ do
            atomically $ unGetTChan chan c
            fun chan con
            )

now it works for me. thanks

Was it helpful?

Solution

I think you have a missleading design. Try to separate to catch-clause to the only action that may throw an exception. For instance, if reading c can't cause an exception, why not separate the catch-clauses?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top