Skip to content
CCPEDIAby Unity Nodes
App Development

Is there a way to catch all exceptions?

6 posts775 views4 likesLast activity Oct 2022

  1. bernhardOP

    When 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?

  2. cocreature

    No, you can only catch specific exception types atm. see below

  3. cocreature 2

    Apologies, 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"
    
  4. Arne_Gebert

    Is 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"
    
  5. cocreature 1

    message 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
    
  6. a_putkov 1

    @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 ()