On Thu, Nov 7, 2013 at 1:20 PM, Klaus Aehlig <[email protected]> wrote:
> 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: Klaus Aehlig <[email protected]>
> ---
>  src/Ganeti/Utils.hs | 12 ++++++++++++
>  1 file changed, 12 insertions(+)
>
> diff --git a/src/Ganeti/Utils.hs b/src/Ganeti/Utils.hs
> index 38db51e..5d5194c 100644
> --- a/src/Ganeti/Utils.hs
> +++ b/src/Ganeti/Utils.hs
> @@ -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: "
> --
> 1.8.4.1
>

LGTM, thanks.

Michele


-- 
Google Germany GmbH
Dienerstr. 12
80331 München

Registergericht und -nummer: Hamburg, HRB 86891
Sitz der Gesellschaft: Hamburg
Geschäftsführer: Graham Law, Christine Elizabeth Flores

Reply via email to