Skip to main content
Version: v0.2.0

Warning and fatal codes

Every deviation the parser notices lands in one of two places, and the split is the whole tolerance model:

  • A warning is data on msg.warnings. The parse still succeeded and the value is still there. Sixteen codes, listed below, exported as HL7_WARNING_CODES.
  • A fatal is a thrown Hl7ParseError. The input is not recoverable as HL7 at all. Four codes, listed below, exported as HL7_FATAL_CODES.

Both registries are a public, versioned contract. A code is never renamed under you without a breaking release, so w.code === HL7_WARNING_CODES.HL7_UNKNOWN_SEGMENT is safe to branch on and safe to persist. Prefer logging w.code and w.position over w.message: the codes are stable, and the messages are bounded but not absolutely content-free (see Troubleshooting).

Every code carries the HL7_ prefix, so a log that mixes our parsers can tell the codes apart. The registries once held the same codes without it. Their old names are still exported for one release, marked deprecated, and each old key now holds the prefixed code, so a comparison written through a registry keeps working. A comparison against a literal string must name the prefixed code.

import { parseHL7, HL7_WARNING_CODES } from "@cosyte/hl7";

// A ZZZ segment is not a standard HL7 segment: tolerated, and surfaced as a warning.
const raw = "MSH|^~\\&|LAB|MAIN|EHR|REF|20260419143000||ADT^A01|EX00003|P|2.5\rZZZ|1";

const msg = parseHL7(raw);

msg.warnings.some((w) => w.code === HL7_WARNING_CODES.HL7_UNKNOWN_SEGMENT); // => true

Warnings​

Emitted by the parser unless the row or the notes below say otherwise. Under { strict: true } every one of them is promoted to a thrown Hl7ParseError instead, whose code is the warning's own code (When a warning becomes a throw).

CodeWhat it means
HL7_MLLP_FRAMING_STRIPPEDThe input arrived wrapped in MLLP transport framing bytes. They were removed before parsing and the message itself is untouched.
HL7_FIELD_WHITESPACE_TRIMMEDLeading or trailing whitespace was trimmed from a field value. The warning carries only the character counts, never the value.
HL7_UNKNOWN_ESCAPE_SEQUENCEAn escape was not recognizable HL7 escape grammar, or ran to end of input unterminated. It is preserved verbatim in the parsed value.
HL7_TIMESTAMP_FALLBACK_FORMATA timestamp did not match the strict HL7 shape, but a declared or built-in fallback format resolved it. Not produced by a parse: see below.
HL7_SEGMENT_CASEA segment identifier carried a lowercase letter. It resolves as the segment it names, and the spelling that arrived is re-emitted unchanged.
HL7_UNKNOWN_SEGMENTNo standard segment carries that name, compared ignoring case, and no active profile claims it as a custom segment either.
HL7_ENCODING_MISMATCHThe encoding characters declared in MSH-2 disagree with the separators the later segments actually used.
HL7_MISSING_EXPECTED_GROUPThe published structure for this message type gives a minimum of one of some segment or group, and the message carries none of it.
HL7_UNKNOWN_CHARSETMSH-18 or a charset override names a value that HL7 Table 0211 does not contain. Bytes are read as latin1 rather than guessed at.
HL7_UNSUPPORTED_CHARSETA recognized Table 0211 set was not decoded, either because it is out of scope here or because a strict decode of it failed.
HL7_ACK_NO_CORRELATION_IDThe inbound message carried no MSH-10 control id, so the built acknowledgment leaves MSA-2 empty instead of inventing one.
HL7_MERGE_MISSING_PRIOR_OR_SURVIVORAn identity merge or move event is missing one side of the prior and surviving pair, or that side carries no usable identifier.
HL7_BATCH_COUNT_MISMATCHA batch or file trailer declares a count that differs from what the splitter found. Nothing is dropped to make the numbers agree.
HL7_BATCH_MISSING_TRAILERAn envelope header opened a scope that no matching trailer segment ever closed. The split still returns every message it found.
HL7_UNTERMINATED_STREAM_MESSAGEThe last message in a stream ended with no segment terminator. It is still yielded in full, but the feed may have been cut off.
HL7_NON_REPEATING_FIELD_REPEATEDA field the standard does not let repeat (PID-35, PID-36 or PID-37) holds more than one repetition. The typed reading is the first; none is dropped from the message.

Some of these are emitted by a surface other than parseHL7, and arrive on that surface's own result rather than on msg.warnings: HL7_ACK_NO_CORRELATION_ID from the acknowledgment builder, HL7_MERGE_MISSING_PRIOR_OR_SURVIVOR from identityEvents(), the two batch codes plus HL7_UNTERMINATED_STREAM_MESSAGE from splitBatch() and parseStream(), and HL7_NON_REPEATING_FIELD_REPEATED from msg.patient, on patient.warnings.

HL7_TIMESTAMP_FALLBACK_FORMAT is another exception, of a different kind: it is a published, stable code with no emit site a parse reaches, so it does not appear on msg.warnings at all. Read matchedFormat on the timestamp instead. It names the format that resolved a non-canonical value, and is absent when the value was canonical HL7 and parsed strictly. The code is documented here because it is exported and would otherwise be an undocumented member of HL7_WARNING_CODES; do not write a check that waits for it to arrive.

Fatals​

Thrown as Hl7ParseError regardless of mode. They mean the bytes are not recoverable as HL7, not that the sender is quirky.

CodeWhat it means
HL7_NO_MSH_SEGMENTThe input carries no MSH header, so there are no delimiters and no message type to read, and nothing that can be parsed.
HL7_MSH_TOO_SHORTThe MSH header is truncated before the fields delimiter discovery needs, so the rest of the message cannot be tokenized.
HL7_INVALID_ENCODING_CHARACTERSMSH-1 and MSH-2 do not yield a usable delimiter set, so every field boundary in the message would have to be a guess.
HL7_EMPTY_INPUTThe input was empty, or held nothing but whitespace, so there is no message present to parse in the first place.

Catch the error and read its code to tell them apart:

import { parseHL7, HL7_FATAL_CODES, Hl7ParseError } from "@cosyte/hl7";

let matched = false;
try {
parseHL7("");
} catch (err) {
matched = err instanceof Hl7ParseError && err.code === HL7_FATAL_CODES.HL7_EMPTY_INPUT;
}

matched; // => true

No error carries text from the input: Hl7ParseError.snippet, which once held up to 40 characters of it, is now always empty and is removed in the next minor release. Results carry input, and the section below names every field never to log.

What is safe to log​

Every message this library reads can carry a patient's identity, so what reaches a log is a choice field by field. The library itself logs nothing.

Safe to logNever log
w.code and err.code, from HL7_WARNING_CODES, HL7_FATAL_CODES and the other error classes; Hl7ParseError.snippet, which is always emptyraw on every entry splitBatch and parseStream return and every failed item readMessages yields: the whole message, verbatim
w.position and err.position (segmentIndex, fieldIndex), Hl7XmlError.offsetraw and fields on a BatchEnvelopeSegment (fileHeader, header, trailer, fileTrailer): the envelope segment, verbatim
Hl7XmlError.path, Hl7EncodeError.charsetraw on a parsed date (DtmParts) and on a DtmAmbiguity: the field as it arrived, a birth date included
msg.meta.type, msg.meta.controlId, msg.version, msg.warnings.length, a date's precisiona field that identifies a person: a name, a record or member number, a birth date, an address, a phone number
index, byteOffset and byteLength on a readMessages item, position on an entryfree text: an NTE note, a narrative OBX value, a Z-segment text field
codes from a code system, counts, lengths and booleans (msg.patient?.mrn !== undefined)a whole message, segment or field: msg.toString(), JSON.stringify(msg), msg.prettyPrint(), msg.get(...)
a result value, a dose or an amount

A failed result is the case to watch. An entry with ok: false carries its error and, beside it, raw, the message it could not parse. Logging the whole entry, or its error together with raw, writes that message to the log. Log entry.error.code and entry.position (for a readMessages item, item.index and item.byteOffset too), and quarantine raw where patient data may be kept, never in a log.

w.message and err.message are bounded rather than content-free: they echo a token from the input only where it has a shape the spec defines, such as a segment id or a message type. Log the code and the position instead. To show what a field holds in a test or an example, read it into a variable or assert on it; never print it.