'How to put error message to out file in XSLT

I am looking for a way to generate additional file with error message in case of processing failure. For example replacement for function concat:

  <xsl:function name="my:concat">
    <xsl:param name="value1" as="node()*"/>
    <xsl:param name="value2" as="node()*"/>
    <xsl:try>
      <xsl:value-of select="concat($value1,$value2)"/>
      <xsl:catch>
        <xsl:value-of select="concat($value1[1],$value2[1])"/>
        <xsl:variable name="LOCALNAME_ERROR" as="xs:string" select="'error.xml'"/>
        <xsl:result-document href="{$LOCALNAME_ERROR}" method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="no">
          <ERROR>
            <DOCID>
              <xsl:value-of select="'DOCID'"/>
            </DOCID>
            <ERRORCODE>
              <xsl:value-of select="$err:code"/>
            </ERRORCODE>
            <ERRORDESCRIPTION>
              <xsl:value-of select="$err:description"/>
            </ERRORDESCRIPTION>
            <FIELDNAME>
              <xsl:value-of select="if (count($value1) &gt; 1) then name($value1[1]) else name($value2[1])"/>
            </FIELDNAME>
            <FIELDPATH>
              <xsl:value-of select="if (count($value1) &gt; 1) then path($value1[1]) else path($value2[1])"/>
            </FIELDPATH>
            <FIELDVALUE>
              <xsl:value-of select="if (count($value1) &gt; 1) then $value1 else $value2"/>
            </FIELDVALUE>
          </ERROR>
        </xsl:result-document>
      </xsl:catch>
    </xsl:try>
  </xsl:function>

So in case of two occurrences it will produce a nice error message with info where error happened.

Test file:

<?xml version='1.0' encoding='ISO-8859-1'?>
<DUMMY_001>
    <field1>value_1</field1>
    <field2>value_abc</field2>
    <field2>value_xyz</field2>
    <field3>value_3</field3>
    <field4>value_4</field4>
</DUMMY_001>

Outcome:

<ERROR>
   <DOCID/>
   <ERRORCODE>err:XPTY0004</ERRORCODE>
   <ERRORDESCRIPTION>A sequence of more than one item is not allowed as the first argument of concat()</ERRORDESCRIPTION>
   <FIELDNAME>field2</FIELDNAME>
   <FIELDPATH>/Q{}DUMMY_001[1]/Q{}field2[1]</FIELDPATH>
   <FIELDVALUE>value_abc value_xyz</FIELDVALUE>
</ERROR>

In saxon 9.9.1.7 the error is: XTDE1480 Cannot execute xsl:result-document while evaluating xsl:function, but in saxon 9.6.0.7 it works. Could you advise if there is a reliable way to create such error messages in the latest saxon versions?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source