Error Handling¶
ClashRS is both a reusable Rust workspace (clash-lib, clash-dns, clash-netstack) and a set of runtime entry points (clash-bin, clash-ffi, REST API). Good error handling keeps failures structured at library boundaries, preserves root causes across async hops, and guarantees that malformed network traffic or a bad reload never crashes the proxy core.
Error Types by Layer¶
Choose the error representation based on the boundary you are implementing:
| Layer / Crate | Error Type | Purpose & Examples |
|---|---|---|
Core public API (clash-lib/src/lib.rs) |
clash_lib::Error (thiserror::Error) & clash_lib::Result<T> |
Typed errors callers can match on: Io, InvalidConfig, ProfileError, DNSError, DNSServerError, Crypto, Operation, Other(anyhow::Error) |
| Sub-domain libraries | Domain thiserror enums |
watfaq_dns::DNSError (clash-dns/src/handler.rs), clash_lib::proxy::ProxyError (clash-lib/src/proxy/mod.rs) |
Data plane (ProxyStream, InboundDatagram, OutboundDatagram, transports) |
std::io::Error |
Integrates directly with Tokio AsyncRead / AsyncWrite and futures::Sink, while preserving io::ErrorKind |
Application & internal glue (clash-bin/src/main.rs, DNS resolver internals, provider parsers) |
anyhow::Result<T> |
Rapid error propagation with rich .context(...) / .with_context(...) chains when callers only display or log the failure |
REST API handlers (clash-lib/src/app/api/) |
HTTP StatusCode + JSON {"message": ...} |
Maps internal errors to client-facing statuses (400, 404, 409, 500) without leaking stack internals |
FFI boundary (clash-ffi/src/lib.rs) |
Error string / c_int return code |
Converts Result to C-safe return values; must never panic across extern "C" |
Core Guidelines¶
1. Never Panic on Untrusted Input or Runtime Failures¶
A proxy continuously processes untrusted bytes from local clients, remote servers, DNS upstreams, remote providers, and REST API requests.
- Avoid
.unwrap()and.expect()on runtime paths—especially when parsing packets, decoding protocol headers, reading configs, or performing filesystem/network I/O. - Propagate recoverable errors with
?,ok_or_else, or explicitmatch. - Reserve
expect("...")only for true programmer invariants that cannot be triggered by external input (and document why the invariant holds in the message), or in#[cfg(test)]. - Watch out for mutex poisoning (
.lock().unwrap()): prefertokio::synclocks when holding across.await, or handle lock acquisition carefully if a panicking thread could poison shared state.
2. Preserve Error Kinds and Source Chains¶
Do not flatten errors into opaque strings too early. Keeping the underlying error type or io::ErrorKind lets callers make accurate operational decisions:
- In
clash-lib/src/proxy/tun/runner.rs, matchingError::Io(e) if e.kind() == io::ErrorKind::PermissionDeniedproduces an actionable privilege error for users instead of a generic failure. - In
clash-lib/src/proxy/naive/datagram.rs, invalid packet lengths returnio::Error::new(io::ErrorKind::InvalidInput, ...)rather thanio::Error::other(...), distinguishing framing bugs from broken transports. - In
clash-lib/src/app/dispatcher/dispatcher_impl.rs, the UDP relay inspectsio::Errorviais_sink_closed(&err)so a permanently closed outbound ends the NAT session immediately instead of logging repeated send errors until timeout.
When formatting an anyhow::Error for operators or API responses, use the alternate display format format!("{e:#}") (as in clash-lib/src/app/api/handlers/config.rs) so the full cause chain (outer: middle: root cause) is rendered instead of only the outermost context.
3. Log OR Return — Avoid Duplicate Logging¶
A common anti-pattern in async networking is logging error!("...") inside a helper function and then returning Err(e), causing every caller up the stack to log the same failure again.
- Low-level helpers and protocol codecs: attach context and return
Err(...); emit at mosttrace!/debug!diagnostics if needed. - Boundary handlers (
Runnerloops, connection dispatchers, API endpoints,main): catch theErr, choose the right log level, and decide how to recover or report it.
4. Match Log Level and Recovery Strategy to Failure Severity¶
| Failure Category | Typical Examples | Recommended Handling |
|---|---|---|
| Normal peer disconnect / noise | UnexpectedEof, ConnectionReset, BrokenPipe, client cancelled request |
Tear down that session cleanly; log at debug! or trace! |
| Recoverable per-request / upstream error | Remote proxy timeout, DNS upstream failure, malformed DNS packet | Isolate to the single flow; answer SERVFAIL (e.g., proxy/dns_hijack.rs) or trigger proxy group failover; log at warn! |
| Startup, reload, or OS environment error | Invalid YAML, safe-path violation, port in use, missing TUN permission | Fail fast (or roll back reload); log clear remediation at error! and return Err to the CLI / API caller |
5. Keep Hot Reloads Atomic on Error¶
Configuration reloads (PUT /configs) must never leave the core half-configured when validation or activation fails. Follow the pattern in clash-lib/src/lib.rs:
- Parse and validate first: run
config.try_parse()(includingSafePathschecks) before touching active components. - Build before swapping: construct
new_componentswhileold_componentscontinues serving traffic. - Roll back on activation failure: if starting the new TUN device or applying runtime settings fails, stop the partially started
new_components, restore the previous TUN state, keepshared_componentspointing toold_components, and return the error over theoneshotchannel to the HTTP handler.
6. Boundary Rules: REST API and FFI¶
- REST API: Return structured JSON (
{"message": "..."}) with accurate status codes (for example,400 Bad Requestfor invalid config payloads,409 Conflictfor disallowed operations such asPOST /restartin--service-mode,500 Internal Server Errorfor internal failures). Never expose sensitive secrets or raw panics in response bodies. - FFI (
clash-ffi): Check incoming pointers for null before dereferencing, convertResulterrors into explicit C strings or integer status codes, and avoid panicking anywhere insideextern "C"functions (unwinding across FFI is undefined behavior).
Review Checklist¶
- [ ] Library and protocol APIs use
thiserrororstd::io::Errorwith meaningful variants /ErrorKind, rather than ad-hoc strings. - [ ]
anyhowerrors attach actionable context via.context(...)/.with_context(...)and format chains with{e:#}at user-facing boundaries. - [ ] No new
.unwrap()/.expect()can be triggered by network peers, config files, or API payloads. - [ ] Each error is logged once at the appropriate boundary and severity (
trace/debugfor peer noise,warnfor transient failures,errorfor actionable failures). - [ ] Failure during config reload or provider refresh leaves the previously working state intact.