Try/Catch

Basic example catching any errors:

xquery version "3.0"; let $x := "Hello" return try { $x cast as xs:integer } catch * { <error>Caught error {$err:code}: {$err:description}</error> }

Generating your own errors:

xquery version "3.0"; declare namespace app="http://exist-db.org/myapp"; declare variable $app:ERROR := xs:QName("app:error"); try { error($app:ERROR, "Ooops", "any data") } catch app:error { <error>Caught error {$err:code}: {$err:description}. Data: {$err:value}.</error> }