Skip to main content

Safe API — Never Throw Exception Variants

Overview​

The UI main thread / batch polling must not be interrupted by an OpcUaException thrown on an RPC failure, so the SDK provides a *_safe variant for each common call — every exception is folded into a StatusCode, which the caller reads from the (StatusCode, 值) tuple (write_safe is the exception: it returns only a StatusCode), so you no longer write try/except.

Corresponding sections of the standard: Browse Part 4 §5.8, Read §5.10.2, Write §5.10.4, Call§5.11.2, HistoryRead Part 11§6.5.

API​

MethodsCategoryReading and WritingNote
ua.browse_safe(node_id, filter)BrowseReadReturns (StatusCode, list[Reference]); if the operation fails, list=[]
ua.read_safe(node_id, attribute)ReadReadReturns (StatusCode, OpcUaDataValue), or value=None on failure
ua.write_safe(node_id, value, attribute)WriteWriteReturns StatusCode (not a tuple)
ua.call_safe(object_node_id, method_node_id, inputs=None)MethodsWriteReturns (StatusCode, list[OpcUaVariant])
ua.read_history_safe(node_id, start_utc, end_utc, max_values=0)HistoryReadReturns (StatusCode, list[OpcUaDataValue])

Authentic signature:

def browse_safe(self, node_id: str, filter: NodeClass = NodeClass.Unspecified)
# -> (StatusCode, List[Reference])

def read_safe(self, node_id: str, attribute: AttributeId = AttributeId.Value)
# -> (StatusCode, Optional[OpcUaDataValue])

def write_safe(self, node_id: str, value, attribute: AttributeId = AttributeId.Value) -> StatusCode

def call_safe(self, object_node_id: str, method_node_id: str, inputs=None)
# -> (StatusCode, List[OpcUaVariant])

def read_history_safe(self, node_id: str, start_utc: datetime, end_utc: datetime,
max_values: int = 0)
# -> (StatusCode, List[OpcUaDataValue])

The four variants that return tuples return when they fail; write_safe (sc, 空值) they return only when they succeed StatusCode.

Code Example​

from datetime import datetime, timedelta, timezone

from darra_opcua import DarraOpcUa, OpcUaVariant, StatusCode # Module Name darra_opcua

with DarraOpcUa("opc.tcp://localhost:4840") as ua:
ua.connect()

# 1) Browse - Deleting a node should not cause an error for the entire tree
st, refs = ua.browse_safe("ns=2;s=Boiler1")
if st != StatusCode.Good:
print(f"Browse 失败 {st}, 跳过")
else:
for r in refs:
print(r.browse_name)

# 2) Batch Polling—A single failure does not interrupt the process
for nid in node_list:
rs, dv = ua.read_safe(nid)
if rs == StatusCode.Good and dv is not None:
with dv:
print(f"{nid} = {dv.value}")
else:
print(f"{nid} = <{rs}>")

# 3) Batch parameter assignment (value must be OpcUaVariant)
for nid, val in setpoints.items():
with OpcUaVariant().set_double(val) as v:
rc = ua.write_safe(nid, v)
if rc != StatusCode.Good:
print(f"写 {nid} 失败 {rc}")

# 4) Calling the method (where `inputs` is a `List[OpcUaVariant]`, not `*args`)
cst, outs = ua.call_safe("ns=2;s=Robot", "ns=2;s=Robot.Home", [])
if cst != StatusCode.Good:
print(f"Home 失败: {cst}")

# 5) History Reading
t1 = datetime.now(timezone.utc)
t0 = t1 - timedelta(hours=1)
hst, vals = ua.read_history_safe("ns=2;s=Temp", t0, t1, max_values=5000)
print(f"历史: {hst}, {len(vals)} 点")

Relationship to the Retry Mechanism​

read_safe / write_safe / browse_safe / call_safe / read_history_safe If a session-level error occurs (BadSessionClosed / BadSessionIdInvalid / BadServerNotConnected / BadConnectionClosed / SecureChannel closed), the system will automatically disconnect and reconnect once before retrying; node-level errors will not be retried.Regular read/write/browse/call/read_history Does not have this layer — Only the "safe" variant includes automatic reconnection.

Best Practices​

  • Safe on the UI main thread — an uncaught OpcUaException is thrown up the call stack.
  • Batch Processing / Safe for Inspection Loops — A Single Point of Failure Does Not Block the Entire Process
  • The business critical path still uses the standard version, allowing exceptions to be explicitly exposed.

Cross-Language Comparison​

C#PythonJavaC++RustC
BrowseSafebrowse_safebrowseSafeBrowseSafebrowse_safeDarraUa_Session_BrowseSafe
ReadSaferead_safereadSafeReadSaferead_safeDarraUa_Session_ReadSafe
WriteSafewrite_safewriteSafeWriteSafewrite_safeDarraUa_Session_WriteSafe
CallSafecall_safecallSafeCallSafecall_safeDarraUa_Session_CallSafe
ReadHistorySaferead_history_safereadHistorySafeReadHistorySaferead_history_safeDarraUa_Session_ReadHistorySafe

Next Step​