Skip to content

Commit df18327

Browse files
committed
Use finally to call Websocket onClose handler
1 parent 6567af8 commit df18327

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

IHP/WebSocket.hs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ import qualified Control.Exception as Exception
2626
import IHP.Controller.Context
2727
import qualified Data.Aeson as Aeson
2828

29+
import qualified IHP.Log.Types as Log
30+
import qualified IHP.Log as Log
31+
2932
class WSApp state where
3033
initialState :: state
3134

@@ -43,14 +46,15 @@ startWSApp connection = do
4346
state <- newIORef (initialState @state)
4447
let ?state = state
4548
let ?connection = connection
46-
let
47-
handleException Websocket.ConnectionClosed = pure ()
48-
handleException (Websocket.CloseRequest {}) = pure ()
49-
handleException e = error ("Unhandled Websocket exception: " <> show e)
50-
result <- Exception.try ((Websocket.withPingThread connection 30 (onPing @state) (run @state)) `Exception.catch` handleException)
51-
onClose @state
49+
50+
result <- Exception.try ((Websocket.withPingThread connection 30 (onPing @state) (run @state)) `Exception.finally` onClose @state)
5251
case result of
53-
Left (Exception.SomeException e) -> putStrLn (tshow e)
52+
Left (e@Exception.SomeException{}) ->
53+
case Exception.fromException e of
54+
(Just Websocket.ConnectionClosed) -> pure ()
55+
(Just (Websocket.CloseRequest {})) -> pure ()
56+
(Just other) -> error ("Unhandled Websocket exception: " <> show other)
57+
Nothing -> Log.error (tshow e)
5458
Right _ -> pure ()
5559

5660
setState :: (?state :: IORef state) => state -> IO ()

0 commit comments

Comments
 (0)