Skip to content

Commit 62dc4a9

Browse files
committed
Add call stack support in ErrorAsException
1 parent 4e66054 commit 62dc4a9

File tree

1 file changed

+33
-11
lines changed

1 file changed

+33
-11
lines changed

cardano-api/src/Cardano/Api/Error.hs

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
module Cardano.Api.Error
99
( Error (..)
1010
, throwErrorAsException
11+
, liftEitherError
1112
, failEitherError
1213
, ErrorAsException (..)
1314
, FileError (..)
@@ -20,7 +21,8 @@ where
2021
import Cardano.Api.Monad.Error
2122
import Cardano.Api.Pretty
2223

23-
import Control.Exception (Exception (..), IOException, throwIO)
24+
import Control.Exception.Safe
25+
import GHC.Stack
2426
import System.Directory (doesFileExist)
2527
import System.IO (Handle)
2628

@@ -32,26 +34,46 @@ instance Error () where
3234

3335
-- | The preferred approach is to use 'Except' or 'ExceptT', but you can if
3436
-- necessary use IO exceptions.
35-
throwErrorAsException :: Error e => e -> IO a
36-
throwErrorAsException e = throwIO (ErrorAsException e)
37-
38-
failEitherError :: MonadFail m => Error e => Either e a -> m a
37+
throwErrorAsException
38+
:: HasCallStack
39+
=> MonadThrow m
40+
=> Typeable e
41+
=> Error e
42+
=> e
43+
-> m a
44+
throwErrorAsException e = withFrozenCallStack $ throwM $ ErrorAsException e
45+
46+
failEitherError
47+
:: MonadFail m
48+
=> Error e
49+
=> Either e a
50+
-> m a
3951
failEitherError = failEitherWith displayError
4052

53+
liftEitherError
54+
:: HasCallStack
55+
=> MonadThrow m
56+
=> Typeable e
57+
=> Error e
58+
=> Either e a
59+
-> m a
60+
liftEitherError = withFrozenCallStack $ either throwErrorAsException pure
61+
4162
data ErrorAsException where
42-
ErrorAsException :: Error e => e -> ErrorAsException
63+
ErrorAsException :: (HasCallStack, Typeable e, Error e) => e -> ErrorAsException
4364

65+
instance Exception ErrorAsException
66+
67+
-- | Pretty print the error inside the exception
4468
instance Error ErrorAsException where
4569
prettyError (ErrorAsException e) =
4670
prettyError e
4771

72+
-- | Pretty print the error inside the exception followed by the call stack pointing to the place where 'Error e' was
73+
-- wrapped in 'ErrorAsException'
4874
instance Show ErrorAsException where
4975
show (ErrorAsException e) =
50-
docToString $ prettyError e
51-
52-
instance Exception ErrorAsException where
53-
displayException (ErrorAsException e) =
54-
docToString $ prettyError e
76+
docToString (prettyError e) <> "\n" <> prettyCallStack callStack
5577

5678
displayError :: Error a => a -> String
5779
displayError = docToString . prettyError

0 commit comments

Comments
 (0)