Abin Abin - 2 months ago 22
Java Question

How can I throw an exception from XSLT?

I want to throw an exception if one tag doesn't contain an attribute.

Answer

In addition to the correct answer of using <xsl:message terminate="yes"/>:

  1. In XSLT 3.0 one can use the new instructions <xsl:try ...> and <xsl:catch ...>: http://www.w3.org/TR/xslt-30/#try-catch

  2. In XSLT 2.0 one can also use the standart XPath function error() to terminate the processing.

Here is an example of using xsl:try and xsl:catch:

<xsl:result-document href="out.xml">
  <xsl:variable name="result">
    <xsl:call-template name="construct-output"/>
  </xsl:variable>
  <xsl:try>
    <xsl:copy-of select="$result" validation="strict"/>
    <xsl:catch>
      <xsl:message>Warning: validation of result document failed:
          Error code: <xsl:value-of select="$err:code"/>
          Reason: <xsl:value-of select="$err:description"/>
      </xsl:message>
      <xsl:sequence select="$result"/>
    </xsl:catch>
  </xsl:try>
</xsl:result-document>