Safe API — Never Throw Exception Variants
Overview
On the OPC UA Server, network jitter, node deletion, permission changes and similar events make the SDK throw an OpcUaException.
Since batch processing (looping through thousands of nodes with Read operations) should not be interrupted by a single failure, a separate exception handler is provided SDK for each RPC common scenario. Safe Version — Any exceptions are collapsed into StatusCode Returns, The business side uses tuple unpacking for parsing; it no longer writes try/catch.
Safe only guarantees no thrown exceptions. All 5 methods are synchronous blocking RPC — the calling thread waits until the server replies or a timeout occurs (requestTimeoutMs, 10 seconds by default). Do not call them directly on a UI thread — the exception is no longer thrown, but the UI still freezes. On a UI thread use await Task.Run(() => ua.ReadSafe(...)), and for long reads use ReadHistoryStreamAsync from Historical Streams.
Corresponding section of the standard:
- Browse — Part 4 §5.8.2
- Read — Part 4 §5.10.2
- Write — Part 4 §5.10.4
- Call — Part 4 §5.11.2
- HistoryRead — Part 11 §6.5
API
| Methods | Category | Reading and Writing | Note |
|---|---|---|---|
| BrowseSafe(nodeId, filter = Unspecified) | Browse | Read | Returns (StatusCode, IReadOnlyList<OpcUaReference>) |
| ReadSafe(nodeId, attribute = Value) | Read | Read | Returns (StatusCode, DataValue), or Value=null on failure |
| WriteSafe(nodeId, value, attribute = Value) | Write | Write | Returns StatusCode (a raw status code, not a tuple) |
| CallSafe(objectId, methodId, params inputs) | Methods | Write | Returns (StatusCode, IReadOnlyList<Variant>) |
| ReadHistorySafe(nodeId, start, end, maxValues = 0) | History | Read | Returns (StatusCode, IReadOnlyList<DataValue>) |
Return Value Conventions:
StatusCode.Good— Business Success, Valid DataBad...— Failure: The data set is empty /Value=null, No throw- Non-Exception SDK → Catch-All
0x80020000(BadInternalError)
BrowseSafe / ReadSafe / CallSafe / ReadHistorySafe are all members of DarraOpcUa. The returned DataValue / Variant still belongs to the caller and must be Dispose.
Code Example
using System;
using System.Collections.Generic;
using DarraOpcUa_Client;
using var ua = new DarraOpcUa("opc.tcp://localhost:4840");
ua.Connect();
var nodeList = new List<string> { "ns=2;s=T1", "ns=2;s=T2", "ns=2;s=T3" };
var setpoints = new List<(string nid, double val)> { ("ns=2;s=SP1", 42.5), ("ns=2;s=SP2", 18.0) };
var t0 = DateTime.UtcNow.AddHours(-1);
var t1 = DateTime.UtcNow;
// 1) BrowseSafe — When a node is deleted during tree refresh, do not cause the entire tree to report an error
var (st, refs) = ua.BrowseSafe("ns=2;s=Boiler1");
if (st != StatusCode.Good)
Console.WriteLine($"Browse 失败 {st}, 跳过此分支"); // For example BadNodeIdUnknown
else
foreach (var r in refs) Console.WriteLine(r.BrowseName);
// 2) ReadSafe — Prevent a single failure from interrupting batch polling
foreach (var nid in nodeList)
{
var (rs, dv) = ua.ReadSafe(nid);
if (rs == StatusCode.Good && dv != null)
using (dv) Console.WriteLine($"{nid} = {dv.Value}");
else
Console.WriteLine($"{nid} = <{rs}>");
}
// 3) WriteSafe — Batch deployment of parameters
foreach (var (nid, val) in setpoints)
{
using var v = new Variant();
v.Double = val;
var rc = ua.WriteSafe(nid, v);
if (rc != StatusCode.Good) Console.WriteLine($"写 {nid} 失败 {rc}");
}
// 4) CallSafe — Return a status code in case of failure, so that exceptions do not interrupt the caller's flow
var (cst, outs) = ua.CallSafe("ns=2;s=Robot", "ns=2;s=Robot.Home");
foreach (var o in outs) o.Dispose(); // Output: Must be disposed of by Variant the caller
if (cst != StatusCode.Good) Console.WriteLine($"Home 失败: {cst}");
// 5) ReadHistorySafe — A single failure in the history curve should not cause the entire dialog box to crash
var (hst, vals) = ua.ReadHistorySafe("ns=2;s=Temp", t0, t1, maxValues: 5000);
foreach (var dv in vals) dv.Dispose(); // The return value is also DataValue passed back to the caller.
Console.WriteLine($"历史: {hst}, {vals.Count} 点");
Relationship to the Retry Mechanism
By default, Read/Write/Browse/Call/ReadHistory when a session-level failure occurs (BadSessionClosed / BadSessionIdInvalid / BadServerNotConnected / BadConnectionClosed / BadSecureChannelClosed), the system automatically reconnects once and then retries; for node-level errors (BadNodeIdUnknown such as ), it does not retry. If the retry still fails, the original exception is thrown.
Safe Variants It will also automatically reconnect, but the exception "Still failed after reconnecting" is collapsed into StatusCode.
Best Practices
- UI Threads should not call Safe directly. — Safe does not throw exceptions, but it may block synchronization, etc. RPC Returns (see the warning at the beginning). Use
await Task.Run(() => ua.ReadSafe(...))to return to UI the thread and update the control. - Safe for Batch Processing / Inspection Cycles — A single point of failure does not block the entire system
- Business Critical Path (e.g., pre-check before starting or stopping equipment) Continue using the standard version, allowing exceptions to be explicitly exposed so that the upper layer can decide whether to retry or abort.
- Don't —
if (status == Good) ... else throwthat would make "Safe" unsafe again; just use the regular version instead.
Cross-Language Comparison
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| BrowseSafe | browse_safe | browseSafe | BrowseSafe | browse_safe | DarraUa_Session_BrowseSafe |
| ReadSafe | read_safe | readSafe | ReadSafe | read_safe | DarraUa_Session_ReadSafe |
| WriteSafe | write_safe | writeSafe | WriteSafe | write_safe | DarraUa_Session_WriteSafe |
| CallSafe | call_safe | callSafe | CallSafe | call_safe | DarraUa_Session_CallSafe |
| ReadHistorySafe | read_history_safe | readHistorySafe | ReadHistorySafe | read_history_safe | DarraUa_Session_ReadHistorySafe |