Error handling
Every error the library throws is one of the typed classes below, each exported from the package barrel. Warnings are data rather than throws unless you ask otherwise: a profile's escalate list promotes only the codes it names.
DicomParseError
Thrown by parseDicom on a Tier-3 fatal code, and on an escalated warning (below). Carries the byte position, the frame that position is counted in, and a registry-composed message. It carries no byte of the input. A code can stand for several structural reasons, and DICOM_INVALID_FILE_META stands for most of them: a File Meta group that cannot be read, and a Data Set after it that is cut short or malformed, such as an element or Item whose declared length reaches past the end of the bytes. The message says which reason; nothing else on the error names it. The message is looked up in a frozen registry and its factories take no tag, no wire-length parameter and no count of the bytes left in the buffer, so none of them can be interpolated. The reason is not that such a fatal fires only on a lying length field: it fires on an honestly truncated file too, where nothing is fabricated and the transport simply lost bytes. Measured on a spec-clean object cut short by two bytes, parseDicom throws DICOM_INVALID_FILE_META for an element whose Value Length reaches past the end of the input, with every declared length in the file honest. The bound covers both because the withheld numbers are four bytes a sender wrote either way, and because on the desynchronized reading those four bytes are somebody's name: an under-declaring ST carrier holding "MR BRAIN SMITHSON " once rendered declared length=1330858068, which is "THSO".
A caller's own mistake is a DicomParseError too, at offset 0 in the "input" frame, so nothing the library throws is a native TypeError or RangeError: DICOM_INVALID_OPTION for an option the call does not take (a stopBeforeTag that is not eight hexadecimal digits, a fallbackCharacterSet outside FALLBACK_CHARACTER_SETS, a maxBytes that is not a positive whole number), DICOM_INVALID_SOURCE for a readDicomHeader source, or a chunk of one, that is not bytes, and DICOM_HEADER_LIMIT_REACHED when readDicomHeader reads maxBytes without reaching its stop. None of the messages echoes the value refused. An error from the file system that readDicomHeader opens a path on (a file that does not exist, say) reaches you as Node raised it.
err.byteOffset locates the element, and err.offsetFrame says which coordinate system that number is counted in (OFFSET_FRAMES: "input", "inflated-dataset", "value-slice"). Only in "input" is it an index into the buffer you passed in. A defined-length Sequence Item is parsed from a slice, so an offset raised inside one counts from that Item, and the same file reports 0, 24, or 40 for the same defect depending on where in the Item it sits. Where a slice begins is deliberately not published, because the distance between two frames is a declared Value Length off the wire. The frame is in the Error.message suffix too, which now reads (offset=N frame=F), so a string match on that suffix stops matching. err.code is unchanged. DicomParseWarning.position still carries no frame beyond its deflated flag, and Element.byteOffset carries none at all: both are pre-existing and neither is closed here. err.snippet is deprecated and always the empty string; it once held up to 16 bytes of the input as hex, and it is removed in the next minor release.
import { parseDicom, DicomParseError, DICOM_FATAL_CODES } from "@cosyte/dicom";
let caught: string | undefined;
try {
parseDicom(Buffer.alloc(0));
} catch (err) {
if (err instanceof DicomParseError && err.code === DICOM_FATAL_CODES.DICOM_EMPTY_INPUT) {
caught = err.code;
}
}
caught; // => "DICOM_EMPTY_INPUT"
When a warning becomes a throw
A Tier-2 warning is escalated to a throw in two ways: { strict: true } escalates every warning, and a profile's escalate list escalates the codes it names (profiles.strict names a set of them). An escalated warning is thrown as a DicomParseError whose code is the warning's own code, such as DICOM_MISSING_PREAMBLE, not a member of DICOM_FATAL_CODES. Its message is the warning's registry message, and byteOffset and offsetFrame locate the warning the same way they locate a fatal. The warning is not also added to ds.warnings, and onWarning does not fire for it.
DICOM_PARSE_STOPPED_BEFORE_TAG and DICOM_CHARSET_ASSUMED are the exceptions and are never escalated. DICOM_PARSE_STOPPED_BEFORE_TAG says a parse given stopBeforeTag stopped where it was asked to, and DICOM_CHARSET_ASSUMED says a parse given fallbackCharacterSet read text under that set. Neither reports a fault in the file, so { strict: true } and a profile's escalate list both leave them warnings.
So err.code is typed DicomFatalCode | DicomWarningCode, not DicomFatalCode alone. Test for the fatal codes you handle and treat any other code as an escalated warning: err.code in DICOM_FATAL_CODES tells the two apart, and a switch over err.code needs a default branch. Do not list every warning code instead: the warning registry grows between releases, so that union is open (see Compatibility).
import { parseDicom, DicomParseError, DICOM_FATAL_CODES } from "@cosyte/dicom";
// Synthetic object with the preamble omitted: a tolerated quirk, escalated here.
const buf = Buffer.from(
"AgAAAFVMBAAcAAAAAgAQAFVJFAAxLjIuODQwLjEwMDA4LjEuMi4xAAgAYABDUwIAQ1QQACAATE8GAE1STi00Mg==",
"base64",
);
let code: string | undefined;
let fatal: boolean | undefined;
try {
parseDicom(buf, { strict: true });
} catch (err) {
if (err instanceof DicomParseError) {
code = err.code;
fatal = err.code in DICOM_FATAL_CODES;
}
}
code; // => "DICOM_MISSING_PREAMBLE"
fatal; // => false
DicomValueError
Thrown only by image.frame(i): DICOM_VALUE_FRAME_INDEX_OUT_OF_RANGE for an index outside [0, numberOfFrames), or DICOM_VALUE_MISSING_REQUIRED_FUNCTIONAL_GROUP when an enhanced object lacks a required geometry macro in both the Per-Frame and Shared groups. Value decode (element.value) never throws. It warns and returns null/typed-absent instead.
DicomSerializeError
Thrown by serializeDicom for DICOM_SERIALIZE_MISSING_TRANSFER_SYNTAX (the dataset names no transfer syntax to write in), DICOM_SERIALIZE_UNSUPPORTED_TRANSFER_SYNTAX, or DICOM_SERIALIZE_INVALID_ENCAPSULATED_PIXEL_DATA (a PS3.5 2026c section A.4 object whose top-level Pixel Data is absent, native, beside Float or Double Float Pixel Data, or a fragment stream section A.4 does not allow: undelimited, an odd or undefined Item Length, or an empty fragment), DICOM_SERIALIZE_DIRECTORY_OFFSET_UNRESOLVED (a DICOMDIR offset the writer cannot tie to a Directory Record the dataset holds, refused rather than written stale or as zero) DICOM_SERIALIZE_DIRECTORY_OFFSET_DEFLATED (a Deflated DICOMDIR carrying a non-zero record offset), or DICOM_SERIALIZE_VALUE_TOO_LONG_FOR_VR (a Private Creator or File Meta value past 65,534 bytes in a VR with a 16-bit length, which PS3.5 forbids writing as UN). The message is a fixed string.
DicomJsonError
Thrown by toDicomJson and fromDicomJson when a value cannot cross between Part 10 and the DICOM JSON Model without being changed or guessed at: DICOM_JSON_UNSUPPORTED_VR, DICOM_JSON_UNSUPPORTED_ELEMENT, DICOM_JSON_UNSUPPORTED_BYTE_ORDER, DICOM_JSON_UNREPRESENTABLE_NUMBER, DICOM_JSON_MALFORMED_VALUE, DICOM_JSON_INVALID_JSON, DICOM_JSON_BULK_DATA_UNRESOLVED, DICOM_JSON_BULK_DATA_URI_REQUIRED, DICOM_JSON_UNSUPPORTED_CHARACTER_SET, DICOM_UNSUPPORTED_TRANSFER_SYNTAX, DICOM_JSON_VALUE_TOO_LONG, DICOM_JSON_VR_MISMATCH, DICOM_JSON_NESTING_TOO_DEEP and DICOM_JSON_CONVERSION_FAILED (DICOM_JSON_ERROR_CODES). No other error leaves either converter: one a callback throws is replaced by DICOM_JSON_CONVERSION_FAILED, and not kept. The message is fixed text and err.tag is the element's tag only when PS3.6 registers it one at a time, "<withheld>" otherwise, so neither carries a value. Serialization says what each code refuses.
import { fromDicomJson, DicomJsonError } from "@cosyte/dicom";
let code: string | undefined;
try {
fromDicomJson(
{ "00100020": { vr: "LO", Value: [42] } },
{ fileMeta: { transferSyntaxUID: "1.2.840.10008.1.2.1" } },
);
} catch (err) {
if (err instanceof DicomJsonError) code = err.code;
}
code; // => "DICOM_JSON_INVALID_JSON"
DicomProfileDefinitionError · DicomDeidentifyError
defineDicomProfile() throws DicomProfileDefinitionError (DICOM_PROFILE_INVALID_DEFINITION, from DICOM_PROFILE_ERROR_CODES) for a structurally invalid profile; deidentify() throws DicomDeidentifyError (DICOM_DEIDENT_INVALID_OPTIONS) for an unknown Retain option or malformed UID root, and DicomDeidentifyError (DICOM_DEIDENT_UNSUPPORTED_TRANSFER_SYNTAX) for a Dataset under one of the four JPIP Referenced syntaxes, whatever the options, because its Pixel Data Provider URL (0028,7FE0) has no PS3.15 Table E.1-1 action and would be kept by omission. Both messages carry only structural facts (option names, the UID root) or a fixed string, never a decoded value.
What is safe to log
A DICOM header is PHI, so a log line takes only what the file cannot put a person into: codes, tags,
VRs, counts, lengths, offsets and the transfer syntax. The tables below name every public field and
method of a parsed data set, of each view and type it reaches, of a warning and of each error, and
say whether it can hold content read from the file; test/docs/safe-to-log-docs.test.ts reads
those members from src/ and fails when one is missing here. "File content" means bytes the sender
wrote, which can identify a person or a study: log none of it, and never log a Dataset, an
Element or a toDicomJson result whole. A field whose type holds a nested data set (an Item) or
a coded concept is file content whole, whatever else sits beside it. The bound behind each
structural field is in
Tolerance,
and the de-identifier's report in
De-identification.
A parsed data set, as parseDicom and readDicomHeader return it:
| Type | Safe to log | File content |
|---|---|---|
Dataset | Dataset.warnings, Dataset.has() | Dataset.patient, Dataset.study, Dataset.series, Dataset.image, Dataset.fileMeta, Dataset.directory, Dataset.get(), Dataset.getAll(), Dataset.elements() |
Item | Item.index, Item.fileOffset; every other member is a Dataset member, as above | none of its own |
Element | Element.tag, Element.vr, Element.vm, Element.length, Element.byteOffset, Element.privateCreator, Element.cp246Promoted, Element.littleEndian, Element.specificCharacterSet | Element.value, Element.rawBytes, Element.items |
PatientView | PatientView.issues | PatientView.id, PatientView.issuerOfId, PatientView.issuerQualifiers, PatientView.otherIds, PatientView.name, PatientView.birthDate, PatientView.sex, PatientView.speciesDescription, PatientView.speciesCode, PatientView.sexNeutered, PatientView.breedDescription, PatientView.breedCode, PatientView.responsiblePerson |
OtherPatientId | none | OtherPatientId.id, OtherPatientId.issuer, OtherPatientId.typeCode |
ResponsiblePerson | none | ResponsiblePerson.name, ResponsiblePerson.role, ResponsiblePerson.organization |
PatientIssue | PatientIssue.code, PatientIssue.tag, PatientIssue.message | none |
StudyView | none | StudyView.instanceUid, StudyView.id, StudyView.accessionNumber, StudyView.date, StudyView.time, StudyView.description |
SeriesView | SeriesView.number, SeriesView.modality | SeriesView.instanceUid, SeriesView.description, SeriesView.frameOfReferenceUid |
ImageView | ImageView.rows, ImageView.columns, ImageView.samplesPerPixel, ImageView.photometricInterpretation, ImageView.planarConfiguration, ImageView.bitsAllocated, ImageView.bitsStored, ImageView.highBit, ImageView.pixelRepresentation, ImageView.signed, ImageView.rescaleSlope, ImageView.rescaleIntercept, ImageView.windowCenter, ImageView.windowWidth, ImageView.pixelSpacing, ImageView.imagerPixelSpacing, ImageView.nominalScannedPixelSpacing, ImageView.sliceThickness, ImageView.spacingBetweenSlices, ImageView.imagePositionPatient, ImageView.imageOrientationPatient, ImageView.numberOfFrames, ImageView.units, ImageView.isEnhancedMultiFrame | ImageView.sopInstanceUid, ImageView.frameOfReferenceUid, ImageView.rescaleType, ImageView.modalityLutSequence, ImageView.voiLutSequence, ImageView.realWorldValueMaps, ImageView.frame() |
FrameFunctionalGroups | FrameFunctionalGroups.index, FrameFunctionalGroups.pixelMeasures, FrameFunctionalGroups.planePosition, FrameFunctionalGroups.planeOrientation, FrameFunctionalGroups.frameVoiLut | FrameFunctionalGroups.pixelValueTransformation |
RealWorldValueMap | RealWorldValueMap.slope, RealWorldValueMap.intercept | RealWorldValueMap.unitsCode |
CodedConcept | CodedConcept.schemeUid | CodedConcept.codeValue, CodedConcept.codingSchemeDesignator, CodedConcept.codeMeaning |
FileMeta | FileMeta.transferSyntaxUID | FileMeta.mediaStorageSOPClassUID, FileMeta.mediaStorageSOPInstanceUID, FileMeta.fileMetaInformationVersion, FileMeta.implementationClassUID, FileMeta.implementationVersionName, FileMeta.sourceApplicationEntityTitle, FileMeta.extraElements |
FileMetaRawElement | FileMetaRawElement.tag, FileMetaRawElement.vr | FileMetaRawElement.value |
DicomDirectory | none | DicomDirectory.records, DicomDirectory.root |
DirectoryRecord | DirectoryRecord.index, DirectoryRecord.type | DirectoryRecord.referencedFileId, DirectoryRecord.lowerLevel, DirectoryRecord.item |
What sits behind the table:
- The patient view is read from the file in every field but
issues: the name, the ID and its issuer, the birth date, the sex, the species and breed, the responsible person. APatientIssue's message is built from its code and the view's own tag constant alone. Dataset.get(),Dataset.getAll()andDataset.elements()return anElement, whose value is the sender's.Element.tag,Element.vr,Element.vm,Element.lengthandElement.byteOffsetare structure, safe to log on a well-formed file; a declared length that lies can make the reader take bytes of a value for a header, and then the tag and the VR are those bytes.Element.privateCreatoris safe to log: it reads<withheld>unless the active profile names the creator.FileMeta.transferSyntaxUIDis one of a closed set of syntaxes, safe to log: a parse goes on only for a syntax it supports and throwsDICOM_UNSUPPORTED_TRANSFER_SYNTAXfor any other. The other File Meta UIDs, the implementation name and the Application Entity Title are what the sender wrote, andfileMetaInformationVersionis two bytes it wrote.ImageView.rescaleTypeis a Long String (LO) the sender writes.modalityLutSequenceandvoiLutSequenceare whole nested data sets, with the LUT Explanation(0028,3003)free text and the LUT Data.realWorldValueMapsand every coded concept carry the Code Meaning(0008,0104)free text.frame()returns a frame's functional groups, whose Pixel Value Transformation carries that frame's Rescale Type. The geometry fields are numbers: sizes, bit depths, rescale and window numbers, spacings, and the position and direction cosines of the image plane in the patient coordinate system.SeriesView.modality,ImageView.photometricInterpretation,ImageView.units,DirectoryRecord.typeandElement.specificCharacterSetare Code Strings (CS) that PS3.3 gives defined terms for, such asCT,MONOCHROME2,BQML,PATIENTandISO_IR 100. The views keep them as written and do not check them against those terms.CodedConcept.schemeUidis not read from the file: the library sets it from its own table for four coding scheme designators, and leaves it absent for any other.Dataset.directoryis absent unless the object is a DICOMDIR.DirectoryRecord.referencedFileIdis a path read from the file, andDirectoryRecord.itemis the record's own data set, with the patient, study and series keys a DICOMDIR repeats.
A warning, DicomParseWarning, on ds.warnings, through onWarning, and on a decoded value's
own warnings:
| Type | Safe to log | File content |
|---|---|---|
DicomParseWarning | DicomParseWarning.code, DicomParseWarning.message, DicomParseWarning.position, DicomParseWarning.expected, DicomParseWarning.profile | none |
DicomPosition | DicomPosition.byteOffset, DicomPosition.fileMeta, DicomPosition.deflated, DicomPosition.contextPath | none |
DicomParseWarning.code: safe to log, a member ofDICOM_WARNING_CODES.DicomParseWarning.message: safe to log. It comes from a frozen registry, and the only things substituted into it are a tag PS3.6 registers, one of the 34 VRs and numbers the parser counted. The one exception is named in theWARNING_MESSAGESdocblock insrc/parser/warnings.ts: the File Meta group length a sender declared.DicomParseWarning.expectedandDicomParseWarning.profile: safe to log. A flag, and the name of the profile that expected the warning, which is the name you gave the profile, never the file.DicomParseWarning.position.byteOffset: safe to log, an offset the parser counted.DicomParseWarning.position.fileMetaandDicomParseWarning.position.deflated: safe to log, flags the parser sets when the offset is inside the File Meta group or into the inflated data set.DicomParseWarning.position.contextPath: safe to log. Only the DICOMDIR record checks set it, to the Directory Record Sequence tag, an Item index and the tag of the offset attribute at fault.
Each error:
| Error | Safe to log | File content |
|---|---|---|
DicomParseError | DicomParseError.code, DicomParseError.message, DicomParseError.byteOffset, DicomParseError.offsetFrame, DicomParseError.contextPath, DicomParseError.snippet (deprecated, always empty) | none |
DicomValueError | DicomValueError.code, DicomValueError.message: a frame index and a frame count | none |
DicomSerializeError | DicomSerializeError.code, DicomSerializeError.message: fixed text | none |
DicomJsonError | DicomJsonError.code, DicomJsonError.message, DicomJsonError.tag: a tag PS3.6 registers one at a time, else "<withheld>" | none |
DicomProfileDefinitionError | DicomProfileDefinitionError.code, DicomProfileDefinitionError.message, DicomProfileDefinitionError.profileName: what the profile's author wrote, never the file | none |
DicomDeidentifyError | DicomDeidentifyError.code, DicomDeidentifyError.message: the option names and the UID root you passed, or fixed text | none |
DicomParseError.contextPath is the warning's own position.contextPath when the error is an
escalated warning, and absent on a fatal. An escalated warning keeps its warning's message, so
under strict or a profile that escalates it, DICOM_FILE_META_GROUP_LENGTH_MISMATCH throws a
DicomParseError whose message holds the File Meta group length the sender declared, as the
warning's message does.
The de-identifier's report, DeidentifyReport, is not safe to log whole. DeidentifyReport.uidMap
holds the source UIDs read from the file, which is file content, and the other fields that can hold
bytes of the file are named on the type and in
De-identification.