Search code examples
haskellhaskell-snap-frameworkhttpexception

Catch HTTPException within Snap Handler


Within one of my snap handlers I am calling an external resource over HTTP using http-client, which can throw an HttpException. In the simplest case, I just want to catch the error and write to std out while I debug; however, I am having a tough time getting the types lined up.

assignCategories' :: String -> [String] -> Handler App (AuthManager App) String
assignCategories' l_id cats  = do
            let baseAttribs = M.fromList [("id",l_id)]                                                            
            let saveQuery = WMSaveObject {baseAttributesSO= baseAttribs ,relatedSO=relatedObjects}

            -- this is the function that can throw an HTTPException            
            -- runWMSave :: WMQueryObj -> Handler App (AuthManager App) String

            saveresponse <- try $ H.runWMSave saveQuery
            return $ case saveresponse of
                Left  e -> show (e :: HttpException)
                Right r -> r

I've played around with the types, but am generally getting errors like below... is there a best practice for calling HTTP within a handler and catching exceptions?

I'm using Control.Monad.Catch. I tried using Control.Exception's try, but had even more difficulties getting types lined up.

   No instance for (Control.Monad.Catch.MonadCatch
                       (Handler App (AuthManager App)))
      arising from a use of ‘try’
    In the expression: try
    In a stmt of a 'do' block:
      saveresponse <- try $ H.runWMSave saveQuery
    In the expression:
      do { liftIO $ putStrLn l_id;
           let baseAttribs = M.fromList ...;
           let relatedObjects = concatMap makeRelatedRow cats;
           let saveQuery = ...;
           .... }

Thanks, Neil


Solution

  • Problem solved, I used try from MonadCatchIO-transformers and that worked.