Skip to content

Exception handling

Danik edited this page Jun 16, 2026 · 1 revision

Exception handling

All exceptions raised by a mikrotik session derive from a single abstract root, TikConnectionException. Catching that one type lets you handle anything the library throws while talking to a router; more specific catch clauses let you react to individual failure modes.

try
{
    connection.Save(addressList);
}
catch (TikAlreadyHaveSuchItemException)
{
    // duplicate – ignore / update instead
}
catch (TikCommandException ex)
{
    // any other command-level error returned by the router
    Console.WriteLine(ex);
}
catch (TikConnectionException ex)
{
    // connection / login / transport-level error
    Console.WriteLine(ex);
}

All transports (Api, Rest, Telnet/Ssh CLI, WinboxCli, WinboxNative, …) translate their internal/protocol-specific errors into this same set of public exception types, so error handling code is identical regardless of which transport a connection uses.

Hierarchy

System.Exception
└── TikConnectionException                          (abstract) — root: any exception from a mikrotik session
    ├── TikConnectionNotOpenException               command issued on a connection that is not open
    ├── TikConnectionLoginException                 login failed (invalid credentials / auth error)
    ├── TikConnectionSSLErrorException              API-SSL not properly configured on the router
    ├── TikConnectionCapabilityNotSupportedException feature used on a transport that lacks the capability
    ├── TikSentenceException                        response sentence is not in the expected format
    ├── WinboxFieldResolutionException              WinBox-native field name cannot be mapped to an M2 key
    └── TikCommandException                         (abstract) — error tied to a specific command
        ├── TikCommandTrapException                 router returned an error (!trap) — generic router refusal
        │   ├── TikNoSuchCommandException           invalid command / syntax ("no such command")
        │   ├── TikNoSuchItemException              item with the given id was not found ("no such item")
        │   └── TikAlreadyHaveSuchItemException     duplicate ("already have such …")
        ├── TikCommandFatalException                router returned a fatal error (!fatal)
        ├── TikCommandAbortException                command was aborted / timed out
        ├── TikCommandUnexpectedResponseException   response shape/framing was not what the command expected
        └── TikCommandAmbiguousResultException      exactly one item expected but more than one was returned

When each is thrown

Connection / session level — TikConnectionException (direct subclasses)

Exception Thrown when
TikConnectionNotOpenException A command is executed before Open() (or after the connection was closed).
TikConnectionLoginException Authentication fails — wrong user/password, or the router rejects the login handshake. The original cause is wrapped as InnerException.
TikConnectionSSLErrorException The TLS handshake fails because API-SSL is not correctly set up on the router. See SSL connection.
TikConnectionCapabilityNotSupportedException A feature is used on a transport that does not advertise the required TikConnectionCapability (e.g. Safe Mode, streaming, listen, tagging, raw commands on a CLI transport). The unsupported Capability is exposed on the exception. Check support up front with connection.Supports(...).
TikSentenceException A sentence received from the router cannot be parsed or is missing an expected word/field. Usually indicates a protocol mismatch or a malformed response.
WinboxFieldResolutionException (WinBox-native only) An API field name cannot be unambiguously mapped to an M2 key. The message explains how to recover (session override or use a WinboxCli connection).

Command level — TikCommandException

TikCommandException is the abstract base for everything that goes wrong while running a specific command. It exposes the offending Command and overrides ToString() to include the command text, parameters and response.

Exception Thrown when
TikCommandTrapException The router answered with an error sentence (!trap). This is the generic "router refused the command" type and carries Code / CodeDescription. It is also the fallback for any router-reported error that does not match a more specific subtype, across all transports.
TikNoSuchCommandException The command path/syntax is invalid ("no such command").
TikNoSuchItemException An operation targets an id that does not exist ("no such item"), or LoadSingle/LoadById finds nothing.
TikAlreadyHaveSuchItemException An insert collides with an existing record ("already have such address", "already have device with such name", …).
TikCommandFatalException The router returned a fatal error (!fatal), e.g. the session was torn down.
TikCommandAbortException The command was aborted (cancelled) or did not finish within the configured timeout.
TikCommandUnexpectedResponseException The response did not have the shape the command required (e.g. a single row was expected but several were returned at the protocol level, or framing was wrong). This is a protocol-shape error, distinct from a router-reported !trap.
TikCommandAmbiguousResultException A single-result API (LoadSingle, ExecuteSingleRow, …) matched more than one item. The count is included in the message.

Transport translation (internal exceptions)

Two exceptions never reach your code — they are internal transport details that are caught and re-thrown as one of the public types above:

  • TikEofException (private, : IOException) — the API socket reported end-of-stream mid-read; translated to a !fatal / TikCommandFatalException.
  • WinboxM2OperationException (internal) — a WinBox-native M2 CRUD call returned a non-zero status. It carries the numeric M2 error code and the router's error string, and WinboxNativeConnection.TranslateM2Error maps it to the matching public type:
    • already existsTikAlreadyHaveSuchItemException
    • object nonexistent / no suchTikNoSuchItemException
    • anything else → TikCommandTrapException (generic router error, same as the API/CLI/REST fallback)

This translation is what guarantees that error-handling code written against the public hierarchy behaves identically on every transport.

Notes

  • The library does not implement [Serializable] / ISerializable on its exception types. The targets (netstandard2.0/2.1) and modern .NET no longer use BinaryFormatter, and several exceptions carry non-serializable members (ITikCommand, ITikSentence). Use ToString() (or your logging framework) to capture full detail.
  • TikCommandException.ToString() is null-safe with respect to its Command.

Clone this wiki locally