Is there a way to catch all exceptions?
App Development6 posts718 views4 likesLast activity Oct 2022
BE
bernhardOP
Dec 2021When I write
try do
...
catch
_ -> do
...
I get error
Ambiguous type variable ‘e0’ arising from a use of ‘DA.Internal.Desugar.fromAnyException’
prevents the constraint ‘(DA.Internal.Desugar.HasFromAnyException
e0)’ from being solved.
Is there any way to catch all, or do I have to explicitly list all options?
CO
cocreature
Dec 2021No, you can only catch specific exception types atm. see below
CO
cocreature
Dec 2021Apologies, I blanked for a minute, that was completely wrong. You can catch AnyException to catch everything. To convert to a specific exception type afterwards use fromAnyException, .eg.
module Main where
import DA.Assert
import Daml.Script
f : () -> Script Text
f () =
try do
x <- fail "abc"
pure "unreachable"
catch
(ex : AnyException) -> pure "caught"
test = do
x <- f ()
x === "caught"
AR
Arne_Gebert
Oct 2022Is there a way to get the text of the exception when catching it generically?
E.g., the following naive approach didn’t work:
module Main where
import DA.Assert
import Daml.Script
f : () -> Script Text
f () =
try do
x <- fail "abc"
pure "unreachable"
catch
(ex : AnyException) -> pure ex.message
test = do
x <- f ()
x === "caught"
CO
cocreature
Oct 2022message is not a record field here. It’s a method of the HasMessage typeclass implemented by all exceptions. So you want something like this:
message ex
A_
a_putkov
Oct 2022@Arne_Gebert
To add to @cocreature 's reply, the value of x in your test will be “abc”, not “caught”. Try the following
f : () -> Script Text
f () = do
try do
x <- fail "abc"
pure "unreachable"
catch
(ex : AnyException) -> pure $ message ex
test : Script ()
test = do
x <- f ()
x === "abc"
pure ()