Skip to Content
go-dicom(3)

Configuration and errors

Where go-dicom logs and how to change it, what the config package's settings do, how errors are shaped across the library, and the limits to set before reading input you do not trust. It is for anyone putting go-dicom into a service or a tool that others feed files to.

Overview

The library has little global state. A read is configured by its ReadOptions, a call by its arguments and its context.Context. What is global is the default logger, config.Logger, and two validation modes, each of which a context can override for one call.

Errors come in three shapes, and every package uses the same ones:

ShapeTest withExample
A sentinelerrors.Is(err, pkg.ErrX)filereader.ErrTruncated, dataset.ErrLossyNotAllowed, fileset.ErrInvalidFileID
A typed error with fieldserrors.As(err, &target)*filereader.ValueTooLongError, *fileset.MissingUIDError, *volume.Error
A kind, a fixed set of causesfilereader.ErrorKind(err), volumeErr.KindReadErrorTruncated, volume.KindGap

Wrap an error with %w when you add context to it, and errors.Is and errors.As still find what is inside.

Logging

config.Logger is a *slog.Logger that writes text to standard error at level WARN and above. What the library logs is a warning about the input: a truncated file, a character set guessed, a retired attribute added to a data set. The reader also logs some detail at DEBUG, which the default level hides.

Replace the default logger

// At startup, before any other goroutine uses the library.
config.SetLogger(slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})))

config.SetDebug(true, w) replaces it with a text logger at DEBUG writing to w (standard error when nil), and SetDebug(false, w) with one at WARN. config.LoggerFromContext(ctx) is the logger a call given ctx uses.

Warning

SetLogger and SetDebug assign a package variable with no lock. Call them once, before other goroutines read or write files, not while work is under way. For a logger per request or per file, use the two ways below, which change nothing global.

A logger for one read

ReadOptions.Logger takes everything a read logs, and what GetDataset logs later for the file it returned. Nothing from that read reaches config.Logger:

var buf bytes.Buffer
f, err := os.Open("chrFrenMulti.dcm")
if err != nil {
	return err
}
df, err := filereader.ReadDICOMFileWithOptions(filebase.NewFileReader(f), filereader.ReadOptions{
	Logger: slog.New(slog.NewTextHandler(&buf, nil)),
})
f.Close()
if err != nil {
	return err
}
ds := df.GetDataset() // logs to the read's logger too
fmt.Print(buf.String())
fmt.Println(len(df.Warnings), "warning(s) on the file;", ds.Length(), "elements")

On pydicom's chrFrenMulti.dcm, which holds the retired Other Patient IDs:

time=… level=WARN msg="dataset: semantic validation" tag=(0010,1000) err="tag (0010,1000) (Other Patient IDs) is retired"
1 warning(s) on the file; 35 elements

slog.New(slog.DiscardHandler) reads silently. The read logs tags, VRs, lengths and offsets, never the bytes or text of a value, since a file from an untrusted source writes what it likes there.

Tip

Act on DICOMFile.Warnings, Truncated, Overrun and TagOrderViolations, not on the log. Everything a program should know about a read is in those fields as well; the log is for someone watching.

A logger for one call

config.WithLogger(ctx, logger) returns a context that carries a logger. The functions and methods that end in WithContext log to it instead of config.Logger:

PackageFunctions and methods taking a context
datasetAddWithContext, AddSequenceWithContext, GetTextValueWithContext, GetPersonNameWithContext, SetTextValueWithContext, GetCharacterSetWithContext, FromDICOMJSONWithContext, FromDICOMJSONStringWithContext and the rest
charsetConvertEncodingsWithContext, DecodeBytesWithContext, EncodeStringWithContext, DecodePersonNameWithContext, EncodePersonNameWithContext, NewCharacterSetWithContext
filereader/attributesTextEncodingsWithContext, DecodeTextWithContext, DICOMJSONWithContext
dataelemGetTextValueWithContext, GetPersonNameValueWithContext, SetTextValueWithContext, SetPersonNameValueWithContext

The same context carries the validation modes, below. A function without WithContext uses context.Background(), and so config.Logger and the global modes.

Validation modes

A mode says what happens when a value cannot be handled as asked:

ModeEffect
config.IGNOREGo on, saying nothing
config.WARNGo on, and log a warning. The default for both modes
config.RAISEReturn an error

There is a reading mode and a writing mode. Set them for the process with config.Get().SetReadingValidationMode(mode) and SetWritingValidationMode(mode), or for one call with a context:

Context functionGives
config.WithReadingValidationMode(ctx, mode)That reading mode
config.WithWritingValidationMode(ctx, mode)That writing mode
config.StrictReading(ctx), StrictWriting(ctx)RAISE for one of them
config.StrictValidation(ctx)RAISE for both
config.DisableValueValidation(ctx)IGNORE for both

A mode in the context wins over the global one. config.ParseValidationMode reads "ignore", "warn" or "raise", and config.Reset() restores every setting's default.

What the modes govern on this branch is the charset package, and the dataelem.DataElement.ValidateWithConfig method a caller can run:

  • The writing mode decides what encoding a string into a set that cannot hold it does. Under WARN or IGNORE it returns the string's UTF-8 bytes and no error, which is wrong under any declaration but UTF-8; under RAISE it returns an error (Character sets).
  • The reading mode decides what an unknown Specific Character Set term does when the charset functions are called with one: fall back to ISO-8859-1, or, under RAISE, return a *errors.DicomUnicodeDecodeError.
ctx := config.StrictReading(context.Background())
_, err := charset.ConvertEncodingsWithContext(ctx, []string{"ISO_IR 999"})
var decodeErr *dcmerrors.DicomUnicodeDecodeError
if errors.As(err, &decodeErr) {
	fmt.Println("unknown character set:", decodeErr.Encoding)
}

It prints unknown character set: ISO_IR 999.

Note

The reading mode does not change what a file read gives. A file whose character set is unknown is decoded as ISO-8859-1 with a warning on DICOMFile.Warnings under every mode, and bytes the declared set cannot map become U+FFFD under every mode, RAISE included.

Settings that change nothing

config.Settings has more fields than the two modes, copied from pydicom's settings: UseDSDecimal, UseDSNumpy, UseISNumpy, AllowDSFloat, DatetimeConversion, ShowFileMeta, ReplaceUNWithKnownVR, ConvertWrongLengthToUN, InferSQForUNVR, InvalidKeywordBehavior, InvalidKeyBehavior, AssumeImplicitVRSwitch, UseNoneAsEmptyTextVR, ApplyJ2KCorrections and BufferedReadSize. They can be set and read back, and no code in the library reads them. The same holds for the pixel data handler registry (config.RegisterPixelDataHandler, FindPixelDataHandler): the decoders do not consult it.

Important

Do not rely on these fields. A read is controlled by ReadOptions, a transcode by TranscodeOptions, a render by RenderOptions; that is where a choice takes effect.

Errors

Reading

A read that fails returns an error with a kind and a sentinel; one that reaches a limit returns a typed error with the tag and offset. Reading and writing has the table of kinds. A sketch of the usual handling:

func describe(path string, err error) string {
	var tooLong *filereader.ValueTooLongError
	var tooLarge *filereader.HeaderTooLargeError
	switch {
	case errors.As(err, &tooLong):
		return fmt.Sprintf("%s: %s holds %d bytes, over %d", path, tooLong.Tag, tooLong.Length, tooLong.Max)
	case errors.As(err, &tooLarge):
		return fmt.Sprintf("%s: header over %d bytes at offset %d", path, tooLarge.Max, tooLarge.Offset)
	case errors.Is(err, filereader.ErrTruncated):
		return path + ": truncated before the read could go on"
	default:
		// A fixed phrase, with nothing from the file in it.
		return fmt.Sprintf("%s: %s", path, filereader.ErrorKind(err))
	}
}

Caution

A read's Error() text can quote what the file held: a tag's name, a length, a transfer syntax UID it did not know. For a file you do not trust, log or show filereader.ErrorKind(err).String() rather than the error itself.

Not every damaged file is an error. A truncated file usually reads, with Truncated set and the elements before the damage intact, and a file that is not DICOM at all reads as a raw data set with HasPreamble false and Truncated set. Check those fields after a read that succeeded.

Other packages

PackageSentinels (errors.Is)Typed errors (errors.As)
filereaderErrTruncated, ErrBadPreamble, ErrBadFileMeta, ErrMalformedElement, ErrNestingTooDeep, ErrBadDeflate, ErrValueTooLong, ErrHeaderTooLarge, ErrVideoFrames*ReadError (with Kind), *ValueTooLongError, *HeaderTooLargeError
dataset (pixel data)ErrLossyNotAllowed, ErrNoEncoder, ErrUndecodedSyntax, ErrNoPixelDescription, ErrPixelSizeOverflow, ErrNotRepresentable, ErrUnsupportedICCProfile*ICCProfileError
compressErrFrameMismatch, ErrJPEGXLNotDecoded
filesetErrInvalidFileID, ErrDuplicateFileID, ErrDuplicateSOPInstance, ErrMissingUID, ErrTooManyRecords, ErrNotDICOM, ErrNoFileMeta*MissingUIDError
srErrNotKeyObjectSelection, ErrTooManyReferences, ErrMalformedKeyObjectSelection
anonymizeErrImplausibleRedaction, ErrJPEGSegmentsNotSearched, ErrJPEGSegmentOverlong
volume*Error, with Kind (KindNoSlices and the rest) and Source
charset, encaps*errors.DicomUnicodeDecodeError, *errors.EncapsulationError

A typed error that has a sentinel matches it too: a *MissingUIDError is ErrMissingUID to errors.Is, and an *ICCProfileError with Unsupported set is ErrUnsupportedICCProfile. For example, with a transcode:

_, err := ds.Transcode("1.2.840.10008.1.2.4.50", dataset.TranscodeOptions{})
switch {
case errors.Is(err, dataset.ErrLossyNotAllowed):
	fmt.Println("refused: JPEG Baseline loses, and no quality was given")
case errors.Is(err, dataset.ErrNoEncoder), errors.Is(err, dataset.ErrUndecodedSyntax):
	fmt.Println("not possible here:", err)
case err != nil:
	return err
}

The errors package

github.com/amrshadid/go-dicom/errors defines DicomError, an interface with ErrorCode() and Details(), and types such as InvalidDicomError, InvalidVRError and DicomUnicodeDecodeError that implement it. On this branch only charset, in RAISE mode, and encaps return them; the other packages return the sentinels and types in the table above. Import it under another name (dcmerrors) beside the standard errors.

Limits for untrusted input

Some limits are always on. Others are off until you set them, because a limit that suits a phone app refuses a whole-body CT.

LimitDefaultSet it to
ReadOptions.MaxValueLengthnoneThe longest value you will hold, such as 16 MiB; refused before it is allocated
ReadOptions.MaxHeaderBytesnoneWhat a parsed header may hold, such as 64 MiB; counts every element, item and value held
ReadOptions.SkipBulkDatafalsetrue, when you need the header and not the pixels; Pixel Data of any length is passed over
ReadOptions.Visitnot setA function that discards what you do not need, for headers of any size
fileset.ReadOptions.MaxRecordsnoneThe most DICOMDIR records you will build
sr.KeyObjectSelectionOptions.MaxReferences131072Lower, if a KOS of that many references is not plausible for you
filereader.MaxSequenceDepth64 levelsFixed
filereader.MaxInflatedDatasetSize256 MiBFixed: a deflated data set may not expand past it
compress.MaxDecompressedSize256 MiBFixed: decoded pixel data may not pass it
compress.MaxInflateRatio1000:1, with an 8 MiB floorFixed: a small input may not claim a large expansion

A compressed frame's size is checked against the data set's Rows, Columns and Samples per Pixel before it is decoded, so a small codestream cannot describe a large image. The full list, the network limits included, is in CONFORMANCE.md §7.

Warning

ReadDICOMFile sets none of the optional limits: it holds every value in memory, bounded only by the size of the file, or for a stream of unknown size by how much arrives. A large file, or a header of a million small sequence items, fills memory as surely as a large value. Use ReadDICOMFileWithOptions with MaxValueLength and MaxHeaderBytes for any file you did not make (Reading and writing).

DICOM JSON and XML are parsed whole by FromDICOMJSONString and FromDICOMXML, which set no bound of their own; limit the bytes you pass them, with io.LimitReader or the request size of your server.

Limits and gotchas

  • The global logger is not synchronized. Set it at startup; use ReadOptions.Logger or config.WithLogger for anything per request.
  • Warnings are data. Read them from the DICOMFile; do not parse the log.
  • The default writing mode is lenient. Encoding text into a non-UTF-8 character set falls back to UTF-8 silently unless the writing mode is RAISE.
  • Most config.Settings fields are inert. Only the two validation modes take effect.
  • An error's text may hold what the file held. Show the kind for a file you do not trust.
  • A failed read is not the only failure. Check HasPreamble, Truncated and Overrun on a read that returned no error.

See also

On this page