error($code, $description, $value) stops evaluation with your own error, named by a QName so callers can tell business-rule failures from system errors. trace($value, $label) returns its value unchanged and logs it (to standard error in Saxon 726,956 ), a probe you can drop into any path. XPath cannot catch errors; XQuery's try/catch and XSLT's xsl:try can, with details in $err:code, $err:description, $err:value and $err:line-number:
cat > price-check.xq <<'EOF'
declare namespace bn = "https://booknest.example.com/ns/errors";
for $b in //book[position() le 3]
return try {
let $p := xs:decimal($b//price)
return if ($p gt 30) then error(xs:QName("bn:PRICE01"), "above cap: " || $p, $b/@id)
else trace($p, "price " || $b/@id || ":")
} catch bn:PRICE01 { "rejected " || $err:value || " (" || $err:description || ")" }
EOF
xquery -s:booknest-catalog.xml price-check.xqOutput
price b1: [1]: xs:decimal: 14.99 price b3: [1]: xs:decimal: 24 14.99 "rejected b2 (above cap: 39.5)" 24
Trace lines appear during evaluation, before the result. catch bn:PRICE01 handles only that code, so a bad cast (FORG0001) still stops the query; add catch * last and log $err:code rather than swallowing it.
Error Functions
Error functions raise custom errors and log diagnostic values during evaluation.| error(fn:QName('http://www.example.com/HR', 'myerr:toohighsal')) | Raises an error, identified by the given QName, which can be caught by a try/catch construct in XQuery or XSLT. |
| trace($v, 'the value of $v is:') | Logs the value of $v together with the given label for diagnostic purposes, then returns $v unchanged. |
merged-01-01-ch03-error-functions.xpath.txt
error(fn:QName('http://www.example.com/HR', 'myerr:toohighsal'))
trace($v, 'the value of $v is:')