Skip to content
Edit this page

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 explicit match.
  • 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()): prefer tokio::sync locks 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, matching Error::Io(e) if e.kind() == io::ErrorKind::PermissionDenied produces an actionable privilege error for users instead of a generic failure.
  • In clash-lib/src/proxy/naive/datagram.rs, invalid packet lengths return io::Error::new(io::ErrorKind::InvalidInput, ...) rather than io::Error::other(...), distinguishing framing bugs from broken transports.
  • In clash-lib/src/app/dispatcher/dispatcher_impl.rs, the UDP relay inspects io::Error via is_sink_closed(&err) so a permanently closed outbound ends the NAT session immediately instead of logging repeated send errors until timeout.
// Preserves the source error in the chain
Message::from_vec(wire).map_err(io::Error::other)?;

// Adds context without discarding the underlying error
let data = tokio::fs::read(&path)
    .await
    .with_context(|| format!("failed to read provider file {}", path.display()))?;
// Loses ErrorKind and the original source error
let data = tokio::fs::read(&path)
    .await
    .map_err(|e| anyhow::anyhow!("read failed: {e}"))?;

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 most trace! / debug! diagnostics if needed.
  • Boundary handlers (Runner loops, connection dispatchers, API endpoints, main): catch the Err, 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:

  1. Parse and validate first: run config.try_parse() (including SafePaths checks) before touching active components.
  2. Build before swapping: construct new_components while old_components continues serving traffic.
  3. 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, keep shared_components pointing to old_components, and return the error over the oneshot channel 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 Request for invalid config payloads, 409 Conflict for disallowed operations such as POST /restart in --service-mode, 500 Internal Server Error for internal failures). Never expose sensitive secrets or raw panics in response bodies.
  • FFI (clash-ffi): Check incoming pointers for null before dereferencing, convert Result errors into explicit C strings or integer status codes, and avoid panicking anywhere inside extern "C" functions (unwinding across FFI is undefined behavior).

Review Checklist

  • [ ] Library and protocol APIs use thiserror or std::io::Error with meaningful variants / ErrorKind, rather than ad-hoc strings.
  • [ ] anyhow errors 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/debug for peer noise, warn for transient failures, error for actionable failures).
  • [ ] Failure during config reload or provider refresh leaves the previously working state intact.