[server] Print exceptions encountered during a connection

This commit is contained in:
Joscha 2020-02-18 00:42:57 +00:00
parent af8305bfac
commit e917893a9b

View file

@ -7,6 +7,7 @@ module Forest.Server
) where ) where
import Control.Concurrent.Chan import Control.Concurrent.Chan
import Control.Exception
import qualified Network.WebSockets as WS import qualified Network.WebSockets as WS
import Forest.Api import Forest.Api
@ -48,18 +49,23 @@ receivePackets conn treeModule = runUntilJustM $ do
act treeModule path act treeModule path
ClientHello _ -> closeWithErrorMessage conn "Invalid packet: Hello can only be sent once" ClientHello _ -> closeWithErrorMessage conn "Invalid packet: Hello can only be sent once"
printException :: SomeException -> IO ()
printException e = putStrLn $ "Encountered exception: " ++ show e
serverApp :: TreeModule a () => Int -> ModuleConstructor (a ()) -> WS.ServerApp serverApp :: TreeModule a () => Int -> ModuleConstructor (a ()) -> WS.ServerApp
serverApp pingDelay constructor pendingConnection = do serverApp pingDelay constructor pendingConnection = do
conn <- WS.acceptRequest pendingConnection conn <- WS.acceptRequest pendingConnection
chan <- newChan chan <- newChan
WS.withPingThread conn pingDelay (pure ()) $ do WS.withPingThread conn pingDelay (pure ()) $ handle printException $ do
firstPacket <- receivePacket conn firstPacket <- receivePacket conn
case firstPacket of case firstPacket of
ClientHello _ -> do ClientHello _ -> do
putStrLn $ "Sending hello reply with " ++ show initialNode putStrLn $ "Sending hello reply with " ++ show initialNode
sendPacket conn $ ServerHello [] initialNode sendPacket conn $ ServerHello [] initialNode
withThread (sendUpdatesThread conn chan initialNode) $ withThread (sendUpdatesThread conn chan initialNode) $
constructor (writeChan chan) $ receivePackets conn constructor (writeChan chan) $ \tm -> do
receivePackets conn tm
putStrLn "Module finished, closing connection"
_ -> closeWithErrorMessage conn "Invalid packet: Expected a hello packet" _ -> closeWithErrorMessage conn "Invalid packet: Expected a hello packet"
where where
initialNode = txtNode "" "Loading..." initialNode = txtNode "" "Loading..."