Tolerance and error handling
Real-world tolerance
Production HL7 traffic routinely violates the published spec: trailing whitespace, MLLP framing, mixed-case segment names, unknown escape sequences, non-canonical timestamps. A parser that rejects those messages is useless on real integrations. Postel's Law applies: the parser is liberal, the emitter is conservative.
Every input the parser reads falls into one of three tiers:
| Tier | Behavior | When | Example codes |
|---|---|---|---|
| 1 | Accepted | Spec-clean input | (none) |
| 2 | Warning | Recoverable deviation | HL7_MLLP_FRAMING_STRIPPED |
| 3 | Fatal (always) | Unrecoverable structural error | HL7_NO_MSH_SEGMENT |
Outside the tiers, a few trivial deviations are normalized silently, with no warning: a segment ended by LF or CRLF instead of CR reads as one ended by CR.
Tier-2 warnings are plain data attached to msg.warnings. Every warning carries a stable string code, a human-readable message, and a position so you can programmatically react to specific deviations. In position, segmentIndex counts the message's segments from 0 (MSH is segment 0), while fieldIndex, repetitionIndex, componentIndex, and subcomponentIndex are 1-indexed HL7 positions:
import { parseHL7, HL7_WARNING_CODES } from "@cosyte/hl7";
const msg = parseHL7("MSH|^~\\&|A|B|C|D|20260101||ADT^A01|1|P|2.5\rZZZ|1");
const [w] = msg.warnings;
w?.code === HL7_WARNING_CODES.HL7_UNKNOWN_SEGMENT; // => true
w?.position; // => { segmentIndex: 1 }
Warning and fatal codes lists every Tier-2 code. Compare against
HL7_WARNING_CODES rather than string literals, so a typo fails to compile.
Need zero tolerance instead? parseHL7(raw, { strict: true }) escalates every Tier-2 deviation to a thrown Hl7ParseError whose code is the warning's own code (When a warning becomes a throw). Use strict in CI validators; leave it off for production ingestion.
The 4 Tier-3 fatal codes (HL7_NO_MSH_SEGMENT, HL7_MSH_TOO_SHORT, HL7_INVALID_ENCODING_CHARACTERS, HL7_EMPTY_INPUT) always throw regardless of mode. They represent inputs the parser can't meaningfully recover from.
Error handling
Six kinds of error are thrown, each a top-level export with a code from its own registry. Narrow with instanceof, then on code:
| Error | Thrown by |
|---|---|
Hl7ParseError | parseHL7 on one of the four fatal codes, and on any warning under { strict: true } |
Hl7ProfileDefinitionError | defineHl7Profile and defineConformanceProfile, for a declaration they refuse |
SchemaTargetError | emitMessageSchema, for a target it does not support |
Hl7EncodeError | msg.toBytes, for a character its character set has no byte for, or a set it has no encoder for |
Hl7XmlError | parseHL7Xml, xmlDataTypes and toHl7Xml, for a document or message they refuse |
Hl7UsageError | a programming error: a malformed dot-path, withField on a segment the message lacks, a bad segment name, removing MSH, or a typed builder missing content its message type requires |
A call the library refuses throws an Hl7UsageError, where it once threw a native TypeError; its code is
one of HL7_USAGE_ERROR_CODES. Hl7ProfileDefinitionError carries a code from
HL7_PROFILE_DEFINITION_ERROR_CODES, and SchemaTargetError one from HL7_SCHEMA_ERROR_CODES; it
echoes the requested target only when the target has the shape of a target name.
Hl7ParseWarning is not thrown: it is the data on msg.warnings.
Hl7ParseError
Thrown by parseHL7 when the input hits one of the four Tier-3 fatal codes, or any warning under { strict: true }. Carries a code and a position, and no text from the input.
import { HL7_FATAL_CODES, Hl7ParseError, parseHL7 } from "@cosyte/hl7";
let error: unknown;
try {
parseHL7("");
} catch (caught) {
error = caught;
}
error instanceof Hl7ParseError; // => true
(error as Hl7ParseError).code === HL7_FATAL_CODES.HL7_EMPTY_INPUT; // => true
(error as Hl7ParseError).position; // => { segmentIndex: 0 }
(error as Hl7ParseError).snippet; // => ""
Hl7ParseError.snippet is always the empty string. It once held up to 40 characters of the input, which could be a patient's name or record number. It is deprecated and removed in the next minor release: read code and position instead.
message is bounded but not absolutely content-free, which is worth stating because message is what a logger prints by default and what stack embeds. A token taken from the input is echoed only when it matches the form the spec defines for it: a three-character segment identifier, an MSH-9 type, an MSH-12 version, or a charset label the closed Table 0211 actually contains. Anything else becomes <withheld>. So a message cannot carry a field's value, but it can carry a residue of up to three characters when a malformed line happens to look like a segment identifier. The other shapes are narrower in practice than their patterns allow, because the library only ever feeds them registry-matched values; the patterns themselves admit more (a message type up to 26 characters, a version up to 14), which matters only if you construct warnings yourself.
Under { strict: true } an escalated Tier-2 warning is thrown as an Hl7ParseError carrying that same bounded message and the warning's position.
When a warning becomes a throw
Under { strict: true } every Tier-2 warning is thrown as an Hl7ParseError whose code is the warning's own code, such as HL7_UNKNOWN_SEGMENT, not a member of HL7_FATAL_CODES. The warning is not also added to msg.warnings, and onWarning does not fire for it.
So Hl7ParseError.code is typed Hl7FatalCode | Hl7WarningCode, not Hl7FatalCode alone. Test for the fatal codes you handle and treat any other code as an escalated warning: err.code in HL7_FATAL_CODES tells the two apart, and a switch over err.code that lists the four fatal codes needs a default branch.
import { HL7_FATAL_CODES, Hl7ParseError, parseHL7 } from "@cosyte/hl7";
let code: string | undefined;
let fatal: boolean | undefined;
try {
parseHL7("MSH|^~\\&|A|B|C|D|20260101||ADT^A01|1|P|2.5\rZZZ|1", { strict: true });
} catch (err) {
if (err instanceof Hl7ParseError) {
code = err.code;
fatal = err.code in HL7_FATAL_CODES;
}
}
code; // => "HL7_UNKNOWN_SEGMENT"
fatal; // => false
Hl7ParseWarning
Tier-2 deviations: plain data, not thrown. Accumulated on msg.warnings and delivered to any onWarning callback in parse order. See the example in Real-world tolerance.
import { type Hl7ParseWarning, parseHL7, type Hl7WarningCode } from "@cosyte/hl7";
function label(w: Hl7ParseWarning): string {
const c: Hl7WarningCode = w.code;
switch (c) {
case "HL7_MLLP_FRAMING_STRIPPED":
return "framed input";
case "HL7_UNKNOWN_SEGMENT":
return "unknown segment";
default:
return c;
}
}
parseHL7("MSH|^~\\&|A|B|C|D|20260101||ACK|1|P|2.5\rMSA|AA|1\rZZZ|1").warnings.map(label); // => ["unknown segment"]
Switch on the Hl7WarningCode union for exhaustive handling: with a switch-exhaustiveness-check lint rule, a missing case is reported.
Hl7ProfileDefinitionError
Thrown by defineHl7Profile() when the options are structurally invalid, and by defineConformanceProfile() for a conformance profile with defects:
import { defineHl7Profile, Hl7ProfileDefinitionError } from "@cosyte/hl7";
let error: unknown;
try {
defineHl7Profile({
name: "broken",
customSegments: { AB: { fields: { foo: 1 } } }, // a custom segment must be a Z-segment
});
} catch (caught) {
error = caught;
}
error instanceof Hl7ProfileDefinitionError; // => true
(error as Hl7ProfileDefinitionError).profileName; // => "broken"
The cases that make defineHl7Profile() throw:
- Missing or non-string
name: every profile must identify itself. - Malformed
customSegmentsorsegmentOverrides: a custom segment must be a Z-segment and an override a standard segment; each field must map to a positive 1-indexed integer; no duplicate field names across merged segments. - Unsupported
dateFormatstokens: tokens must be drawn fromSUPPORTED_DATE_TOKENS(re-exported from the package barrel for introspection). - Unknown option keys: the options bag is closed; typos throw with "did you mean" hints.
The five error classes, the HL7_FATAL_CODES, HL7_WARNING_CODES and HL7_XML_ERROR_CODES registries and the SUPPORTED_DATE_TOKENS set are all top-level exports.