Revision 1091021c

b/htools/Ganeti/BasicTypes.hs
1 1
{-
2 2

  
3
Copyright (C) 2009, 2010, 2011 Google Inc.
3
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
4 4

  
5 5
This program is free software; you can redistribute it and/or modify
6 6
it under the terms of the GNU General Public License as published by
......
25 25
  , isBad
26 26
  , eitherToResult
27 27
  , annotateResult
28
  , annotateIOError
29
  , exitIfBad
28 30
  ) where
29 31

  
30 32
import Control.Monad
33
import System.IO (hPutStrLn, stderr)
34
import System.Exit
31 35

  
32 36
-- | This is similar to the JSON library Result type - /very/ similar,
33 37
-- but we want to use it in multiple places, so we abstract it into a
......
71 75
annotateResult :: String -> Result a -> Result a
72 76
annotateResult owner (Bad s) = Bad $ owner ++ ": " ++ s
73 77
annotateResult _ v = v
78

  
79
-- | Annotates and transforms IOErrors into a Result type. This can be
80
-- used in the error handler argument to 'catch', for example.
81
annotateIOError :: String -> IOError -> IO (Result a)
82
annotateIOError description exc =
83
  return . Bad $ description ++ ": " ++ show exc
84

  
85
-- | Unwraps a 'Result', exiting the program if it is a 'Bad' value,
86
-- otherwise returning the actual contained value.
87
exitIfBad :: Result a -> IO a
88
exitIfBad (Bad s) = do
89
  hPutStrLn stderr $ "Failure: " ++ s
90
  exitWith (ExitFailure 1)
91
exitIfBad (Ok v) = return v

Also available in: Unified diff