Commit 5badb3e7 authored by Klaus Aehlig's avatar Klaus Aehlig

Add utility function tryAndLogIOError

This function allows to use 'IO a' objects in a safe
way, using the 'try' function; the outcome is reported
as a 'Result'. IOErrors are logged and the result is
'Bad', while in the case of no errors, a result-yielding
function is applied to the value.
Signed-off-by: default avatarKlaus Aehlig <aehlig@google.com>
Reviewed-by: default avatarMichele Tartara <mtartara@google.com>
parent 710f5ae2
......@@ -61,8 +61,10 @@ module Ganeti.Utils
, setOwnerAndGroupFromNames
, formatOrdinal
, atomicWriteFile
, tryAndLogIOError
) where
import Control.Exception (try)
import Data.Char (toUpper, isAlphaNum, isDigit, isSpace)
import Data.Function (on)
import Data.List
......@@ -268,6 +270,16 @@ logWarningIfBad msg defVal (Bad s) = do
return defVal
logWarningIfBad _ _ (Ok v) = return v
-- | Try an IO interaction, log errors and unfold as a 'Result'.
tryAndLogIOError :: IO a -> String -> (a -> Result b) -> IO (Result b)
tryAndLogIOError io msg okfn =
try io >>= either
(\ e -> do
let combinedmsg = msg ++ ": " ++ show (e :: IOError)
logError combinedmsg
return . Bad $ combinedmsg)
(return . okfn)
-- | Print a warning, but do not exit.
warn :: String -> IO ()
warn = hPutStrLn stderr . (++) "Warning: "
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment