14.1.1Parser Error Handler


Parser Error Handler validation is enabled by calling IParser#setParserErrorHandler(IParserErrorHandler) on either the FhirContext or on individual parser instances. This method takes an IParserErrorHandler, which is a callback that will be invoked any time a parse issue is detected.

There are two implementations of IParserErrorHandler that come built into HAPI FHIR. You can also supply your own implementation if you want.

  • LenientErrorHandler logs any errors but does not abort parsing. By default this handler is used, and it logs errors at "warning" level. It can also be configured to silently ignore issues. LenientErrorHandler is the default.

  • StrictErrorHandler throws a DataFormatException if any errors are detected.

The following example shows how to configure a parser to use strict validation.

FhirContext ctx = FhirContext.forR4();

// Create a parser and configure it to use the strict error handler
IParser parser = ctx.newXmlParser();
parser.setParserErrorHandler(new StrictErrorHandler());

// This example resource is invalid, as Patient.active can not repeat
String input = "<Patient><active value=\"true\"/><active value=\"false\"/></Patient>";

// The following will throw a DataFormatException because of the StrictErrorHandler
parser.parseResource(Patient.class, input);

You can also configure the error handler at the FhirContext level, which is useful for clients.

FhirContext ctx = FhirContext.forR4();

ctx.setParserErrorHandler(new StrictErrorHandler());

// This client will have strict parser validation enabled
IGenericClient client = ctx.newRestfulGenericClient("http://hapi.fhir.org/baseR4");

FhirContext level validators can also be useful on servers.

public class MyRestfulServer extends RestfulServer {

   protected void initialize() throws ServletException {
      // ...Configure resource providers, etc...

      // Create a context, set the error handler and instruct
      // the server to use it
      FhirContext ctx = FhirContext.forR4();
      ctx.setParserErrorHandler(new StrictErrorHandler());