OptrisOptrisDocumentation

Documentation/OTC SDK/Overviewv12.0

Error Handling

In Fahrenheit: with the SDK switched to Fahrenheit (SetTemperatureUnit() and its counterparts, see Temperatures in Fahrenheit), every temperature on this page is read and written in Fahrenheit, and every difference in Fahrenheit degrees; the samples are unchanged.

Overview

The SDK uses two complementary error reporting mechanisms:

  1. Exceptions for synchronous errors (construction failures, configuration errors, capture timeouts).
  2. Error callback for a failure of the SDK's processing thread, which happens outside any call of yours.

Losing the camera is neither: it is a connection status. See Noticing a Dropped Connection.

Every exception the SDK raises on its own behalf inherits from optris::sdk::SdkException, which inherits from std::exception, so catching SdkException handles them generically while a subclass handles one case in particular. A handful of calls reject their arguments with std::invalid_argument instead; those are listed under Exception Hierarchy and a top-level handler should catch std::exception to be complete.

Note: The whole C++ surface throws, and pif::PifController was the last part of it that did not. Through API version 33 its fifteen fallible calls returned a value-or-error type instead; API version 34 converted them, so there is now one error convention in C++ and no exception to describe. A PIF refusal arrives as pif::PifException, which inherits from SdkException like every other, and carries code(), a PifError saying which refusal it was. One type with a code rather than nine types, because the nine are answers from one device about one request: branch on code(), and read what() for the specifics.

Note: A poll loop still does not need to be a try block, which was the original argument for the old shape and survives the conversion intact. On an interface whose inputs arrive with frames, reading before the first frame is not a refusal: ReadDigitalInput() answers DigitalState::Unknown, ReadAnalogInput() answers NaN, and ReadAll() reports inputs_known false. What throws is a wrong request, which is a wiring fault rather than a per-frame outcome.

pif::PifException is the one type declared outside optris/sdk/exception.h on purpose beside ConfigLoadException: it lives in optris/sdk/pif/pif_controller.h, next to the PifError enumeration its code() returns, because that enumeration is what gives it its meaning. It crosses the C ABI as whatever status its code maps to, which is the same status each PifError has always produced there.

The low-level recording types in optris/sdk/rec/ all throw: Recorder, Player, Snapshot, ContinuousRecorder, SessionRecorder, SessionPlayer, RecordingController, FrameIndex, VideoExporter, OpenSeries() and the metadata parsers, exactly as Imager::Recorder() and Player do. A RecordError decides which exception: see the table below.

Exception Hierarchy

Every class below is defined in optris/sdk/exception.h, with the single exception of ConfigLoadException, which is declared in optris/sdk/config_io.h because it carries a ConfigLoadReport:

std::exception
  └── optris::sdk::SdkException
        ├── optris::sdk::DeviceException
        │     ├── optris::sdk::ConnectTimeoutException
        │     └── optris::sdk::DeviceBusyException
        ├── optris::sdk::CalibrationException
        ├── optris::sdk::ConfigException
        │     └── optris::sdk::ConfigLoadException   (config_io.h)
        ├── optris::sdk::CaptureException
        ├── optris::sdk::IoException
        ├── optris::sdk::InvalidStateException
        ├── optris::sdk::FeatureNotSupportedException
        ├── optris::sdk::PathExistsException
        ├── optris::sdk::InvalidArgumentException
        ├── optris::sdk::FileTooLargeException
        └── optris::sdk::InsufficientSpaceException

The last four are deliberately under SdkException directly rather than under ConfigException or IoException, which would have read more naturally. Each says why at its own declaration, and the reason is the same one every time: a catch (SdkException &) already written keeps catching them, while ConfigException's and IoException's status codes are not what the C ABI documents for these cases.

Exception When Thrown
SdkException Base class. Carries a message() string. Catch this to handle all SDK errors generically.
DeviceException Device not found, not accessible, refused, or failed while being operated. Carries an optional serial() identifying the device.
ConnectTimeoutException Opening a network camera ran out of network.connect_timeout: nothing answered. Derives from DeviceException, so catch it first to tell it apart from a refusal. Only the network transport raises it.
DeviceBusyException The camera would not carry the operation out, and may next time. Derives from DeviceException, so catch it first to tell it from a device that is gone. It is the one exception here where repeating the same call unchanged is a sensible response: an Xi 400 refuses an operation-mode switch with EIO while the previous stream is still tearing down, and the SDK reports "not now" rather than "not valid" after four retries over five seconds.
CalibrationException The open failed, and calibration files were missing along the way. A camera whose files are merely missing still opens; see Calibration File Acquisition.
ConfigException Invalid configuration: a temperature range or operation mode this camera does not have, a calibration_path that does not exist, an invalid serial.
ConfigLoadException A ConfigException from LoadConfig() or the reporting ApplyConfig(): the file or record was refused for this camera, or applied only in part. report() names exactly which sections took effect and which did not.
CaptureException Frame acquisition failure, for example a timeout in AcquireFrame().
IoException File I/O error: a recording that cannot be opened, a configuration file that cannot be written.
InvalidStateException The call is well formed, but not now: starting a recording while one is already running, for instance. Distinct from ConfigException, which means the request itself is wrong, and from FeatureNotSupportedException, which means this camera can never do it. Stop the recording and the same call succeeds.
FeatureNotSupportedException The request is reasonable, but this camera or source does not implement it: a focus position on a camera with no focus motor, for instance. Catching it is how a user interface greys a feature out.
PathExistsException Every argument was well formed and the destination is already taken: StartRecording() on a path that exists refuses rather than overwriting. The remedy is one std::filesystem::remove(), or another name. Distinct from IoException because nothing was read or written; the SDK deliberately did not try.
InvalidArgumentException The request itself is wrong and the message names which part: a continuous recording asked for with no retention bound, a clip whose out point precedes its in point, an empty output directory. Distinct from InvalidStateException, which is the same call being wrong only now.
FileTooLargeException The result would be larger than the destination can hold in one file, which some file systems cap far below the volume's free space. Distinct from IoException and from InsufficientSpaceException because more free space does not help: the remedy is another destination or a smaller attachment. No camera-surface path raises it today, and it is mapped anyway, so the answer cannot change meaning the day one does.
InsufficientSpaceException The destination has less free space than the caller itself asked to keep, so the recording was not started: rec::RecordingOptions::min_free_bytes is set and the volume is below it. The message names both numbers. It is a refusal at the start only; a volume that fills up while a recording runs does not produce it.

A few calls validate their arguments with std::invalid_argument rather than a type from this hierarchy: SetConnectionTimeout() on a non-positive timeout, Radiometry().SetReferenceTemperature() on a temperature at or below -100, Display().SetColorWindow() on an inverted band. Catching SdkException alone does not catch those.

Across the C ABI each of these is a status code (OPTRIS_SDK_ERROR_DEVICE, OPTRIS_SDK_ERROR_TIMEOUT, OPTRIS_SDK_ERROR_BUSY, OPTRIS_SDK_ERROR_CALIBRATION, OPTRIS_SDK_ERROR_CONFIGURATION, OPTRIS_SDK_ERROR_CAPTURE, OPTRIS_SDK_ERROR_IO, OPTRIS_SDK_ERROR_INVALID_STATE, OPTRIS_SDK_ERROR_NOT_SUPPORTED, OPTRIS_SDK_ERROR_ALREADY_EXISTS, OPTRIS_SDK_ERROR_INVALID_ARGUMENT, OPTRIS_SDK_ERROR_OUT_OF_RANGE, OPTRIS_SDK_ERROR_INSUFFICIENT_SPACE), with the message in optris_sdk_last_error_message() and the stable ASCII name of the code in optris_sdk_status_name().

In .NET the same set is ThermalDeviceException (with ConnectTimeoutException and DeviceBusyException under it), CalibrationException, SdkConfigurationException (with ConfigurationLoadException, PathExistsException and InsufficientSpaceException under it), FrameCaptureException (with FrameTimeoutException under it), SdkIOException, SdkObjectNotFoundException and FeatureNotSupportedException, all deriving from OptrisSdkException. OPTRIS_SDK_ERROR_INVALID_ARGUMENT and OPTRIS_SDK_ERROR_OUT_OF_RANGE arrive as SdkConfigurationException rather than as types of their own, which is also what an AlreadyExists or an InsufficientSpace reads as to a broad handler, deliberately. OPTRIS_SDK_ERROR_INVALID_STATE is the one that gets no SDK type at all: it surfaces as .NET's own InvalidOperationException, which does not derive from OptrisSdkException, so a catch (OptrisSdkException) alone will not see it.

When Exceptions Are Thrown

Construction

Imager::Create() and its overloads throw on failure:

// Throws DeviceException if no camera is found or it cannot be opened.
auto imager = optris::sdk::Imager::Create();

// Throws ConfigException for a calibration_path that does not exist,
// ConnectTimeoutException if a network camera does not answer in time.
auto configured = optris::sdk::Imager::Create(config);

// Throws IoException if the file cannot be opened.
auto player = optris::sdk::Player::Open("/data/recording.mkv");

Construction is the primary failure point. If Create() succeeds, the imager is connected and ready to stream, but check GetCalibrationStatus() before trusting its temperatures.

Configuration

Methods that validate parameters throw ConfigException:

// Throws ConfigException if this camera has no such range.
optris::sdk::TemperatureRange range;
range.min_c = -500;
range.max_c = 2000;
imager->SetTemperatureRange(range);

Frame Acquisition

Pull-based methods throw CaptureException on timeout or error:

// Throws CaptureException on timeout.
auto frame = imager->AcquireFrame(std::chrono::milliseconds(100));

TryAcquireFrame() does not block: it returns an empty std::optional when no frame is waiting. Across the ABI the same thing is a zero timeout, which answers OPTRIS_SDK_ERROR_WOULD_BLOCK when nothing is ready. .NET turns that into TryAcquireFrame(out frame) returning false and Python into try_acquire() returning None; from Rust, call acquire_frame(0) and read the status.

Camera Control

Hardware operations throw DeviceException on failure:

// Throws DeviceException if the shutter cycle cannot be triggered.
// The shutter lives on Detector(), not Radiometry().
imager->Detector().TriggerShutter();

// Throws FeatureNotSupportedException on a camera with no focus motor,
// DeviceException if the motor cannot be reached.
imager->Optics().SetFocus(0.5F);  // the middle of the travel

// Throws DeviceBusyException when the camera declines for now and the
// same call would succeed shortly -- on an Xi 400 a mode switch during
// a stream teardown does exactly this. Catch it before DeviceException.
imager->SetOperationMode(mode);

Recording, Playback and Snapshots

Everything under optris::sdk::rec throws, and the exception type says which refusal it was.

namespace rec = optris::sdk::rec;

try {
  auto recorder = rec::Recorder::Create(global);
  recorder->AddVideoStream(stream);
  recorder->OpenOutput();
  recorder->WriteFrame(frame);
} catch (const optris::sdk::PathExistsException& e) {
  // That name is taken. One std::filesystem::remove(), or another
  // name; nothing was read or written.
  std::println(stderr, "{}", e.what());
} catch (const optris::sdk::InsufficientSpaceException& e) {
  // Your own min_free_bytes refused the start. Free space and retry.
  std::println(stderr, "{}", e.what());
} catch (const optris::sdk::SdkException& e) {
  std::println(stderr, "{}", e.what());
}

Catch the derived types before SdkException, which is its base: catch order is source order in C++, so a base-class arm placed first swallows every one of them. Nothing reports that mistake: the compiler does not refuse it and there is no diagnostic at run time, so the arm you wrote for "that name is taken" simply never executes. That is the only ordering rule here: all eight types below derive from SdkException directly, with no sibling deriving from another, so there is no further precedence to get right. If you are replacing a switch on a code with a chain of catch clauses, write them in the order of the table below and keep SdkException last.

The rec::RecordError a refusal carries is what picks the type, and the mapping is one-to-one:

rec::RecordError Exception Across the C ABI
kInvalidState InvalidStateException OPTRIS_SDK_ERROR_INVALID_STATE
kPathExists PathExistsException OPTRIS_SDK_ERROR_ALREADY_EXISTS
kInvalidParameter InvalidArgumentException OPTRIS_SDK_ERROR_INVALID_ARGUMENT
kIoError IoException OPTRIS_SDK_ERROR_IO
kCodecNotFound FeatureNotSupportedException OPTRIS_SDK_ERROR_NOT_SUPPORTED
kFileTooLarge FileTooLargeException OPTRIS_SDK_ERROR_OUT_OF_RANGE
kInsufficientSpace InsufficientSpaceException OPTRIS_SDK_ERROR_INSUFFICIENT_SPACE
kInternal SdkException OPTRIS_SDK_ERROR_UNKNOWN

kInternal is the one that stays the base class, and that is honest rather than a gap: it means an FFmpeg or library failure with nothing a caller can do about it, which is the one case for which OPTRIS_SDK_ERROR_UNKNOWN is the right answer.

Note: The three SaveSnapshot() methods (on Imager::Recorder(), Player and StillSource) are the exception to the table. They raise std::invalid_argument for a rejected argument and IoException for a write failure, and have done since the two were split apart, so a catch (const std::invalid_argument&) already written keeps working. rec::Snapshot's own SavePng(), SaveTiff(), SaveJpeg() and SaveCsv() follow the table.

Callbacks Must Not Throw

A frame callback (SetThermalCallback, SetBgraCallback, etc.) runs on the SDK's processing thread, and an exception escaping it terminates the process. Catch everything inside your callback, and hand anything that needs handling to a thread of your own.

Error Callback

The error callback receives failures of the SDK's processing thread: errors that cannot be reported through exceptions, because they occur outside the caller's stack frame.

imager->SetErrorCallback(
    [](const std::string& message) {
  spdlog::error("SDK error: {}", message);
});

When the processing thread fails, it stops: the message is logged, the error callback is called with it, and no further frames are processed. Recover by reconnecting (Imager::Reconnect()) or by destroying the imager and creating a new one.

A camera that is unplugged or stops sending is not reported here. Use SetConnectionStatusCallback() for that.

The error callback is called on the SDK's internal thread. Keep the handler fast and non-blocking. If you need to perform complex recovery, post the error to your application's main thread.

Thread Safety

  • Exceptions are thrown on the calling thread (the thread that called Create(), AcquireFrame(), TriggerShutter(), etc.).
  • Error callback is called on the SDK's internal processing thread.
  • The error callback must be thread-safe. Do not access non-atomic shared state without synchronization.

DeviceException Details

DeviceException carries an optional serial number identifying the device that caused the error:

try {
  auto imager = optris::sdk::Imager::Create(config);
} catch (const optris::sdk::DeviceException& e) {
  std::println(stderr, "Device error: {}", e.what());
  if (!e.serial().empty()) {
    std::println(stderr, "Device serial: {}",
                 e.serial());
  }
}

The serial is populated when the error is associated with a specific device (e.g., a named camera that could not be opened). It is empty when the error is not device-specific (e.g., "no cameras found").

This is the one thing on this page that is C++ only. The serial is a field of DeviceException, and the C ABI has no entry point that reports it: optris_sdk_last_error_message() returns the message and optris_sdk_last_error_status() the code, and neither carries the device. So .NET, Python and Rust cannot surface it however they are written. An application in those bindings that needs the serial as data has to use the serial it passed in.

Example

Complete error handling pattern covering all failure modes:

#include <optrissdk.h>
#include <chrono>
#include <print>
#include <thread>

int main() {
  std::unique_ptr<optris::sdk::Imager> imager;

  // Phase 1: Construction, handling all creation errors.
  try {
    imager = optris::sdk::Imager::Create();
  } catch (const optris::sdk::DeviceException& e) {
    std::println(stderr, "No camera found: {}", e.what());
    if (!e.serial().empty()) {
      std::println(stderr,
                   "Failed device serial: {}",
                   e.serial());
    }
    return 1;
  } catch (const optris::sdk::CalibrationException& e) {
    std::println(stderr,
                 "Calibration error: {}", e.what());
    return 1;
  } catch (const optris::sdk::SdkException& e) {
    std::println(stderr, "SDK error: {}", e.what());
    return 1;
  }

  // A camera without its calibration files still opens.
  if (!optris::sdk::IsCalibrated(imager->GetCalibrationStatus())) {
    std::println(stderr, "{}", imager->GetCalibrationDiagnosis());
  }

  // Phase 2: Register error callback for async errors.
  imager->SetErrorCallback(
      [](const std::string& message) {
    std::println(stderr,
                 "Async SDK error: {}", message);
  });

  // Phase 3: Configure, handling parameter errors.
  try {
    optris::sdk::TemperatureRange range;
    range.min_c = 150;
    range.max_c = 900;
    imager->SetTemperatureRange(range);
  } catch (const optris::sdk::ConfigException& e) {
    std::println(stderr,
                 "Config error: {}", e.what());
    // Stay in whichever range the camera opened with.
  }

  // Phase 4: Stream, handling capture errors.
  imager->SetThermalCallback(
      [](const optris::sdk::ThermalFrame& f) {
    // Frames from before the startup calibration has finished arrive
    // too, and are not measurements.
    if (!f.GetMetadata().thermal_data_reliable) return;
    try {
      std::println("Max: {:.1f} C", f.GetMaxTemperature());
    } catch (...) {
      // Never let an exception leave a frame callback.
    }
  });

  imager->Start();

  // Phase 5: File I/O, handling save errors.
  try {
    imager->SaveConfig("/tmp/camera_config.json");
  } catch (const optris::sdk::IoException& e) {
    std::println(stderr,
                 "Cannot save config: {}", e.what());
  }

  std::this_thread::sleep_for(std::chrono::seconds(10));
  imager->Stop();
}