How to do error and exception handling in DAML?
- Vivek_SrivastavaOP 3
Similar to JAVA and other languages can I throw Exceptions and errors?
- cocreature 3
EDIT: Since SDK 1.15 and Daml-LF 1.14, Daml now provides native exception handling. Take a look at the documentation for details and examples.
Original Answer:
DAML does not have exceptions in the way they exist in Java. You can abort a transaction by callingabort(or in some other ways, e.g.,error, division by zero, …). But it is not possible to catch that inside of DAML in any way or handle it. If you have errors that you want to handle then you can use theEither a btype, e.g.,Either String bif you just want strings as error messages. An error is then represented usingLeft "this is an error"while a non-error result is just wrapped inRight result. In that case you can handle the error using pattern matching, e.g.,case resultOrError : Either[String, Int] of Left _ -> 42 -- if we got an error, we return 42 Right r -> r -- if we got no error we just return the result - Andreas_Lochbihler 1
Eitheris the canonical way to pass errors around that shall be handled later. Outside of anUpdatecontext, they can be used withdonotation and therefore appear like exceptions. Inside anUpdateexpression, you may want to define anEitherTmonad transformer such that you don’t have to explicitly fiddle with error handling in every step of the update.Note however that a
Leftinside anUpdatedoes not abort the current update and undo the accumulated updates. For example,do archive cid1 x <- fetch cid2 if (someCondition x) then pure () else LeftT "error" ...the transaction will archive
cid1even if thesomeCondition xfails. This is similar to exceptions in languages like Java, where all side effects of the code before the exception remain. This makes reasoning about the code much harder. Very often, you would want to compose update expressions such that they all fail if only one of them raises an error. But this is not possible right now as it conflicts with the DAML privacy model.