rust concurrency_error ai_generated true

called `Result::unwrap()` on an `Err` value: RecvError: receiving on a closed channel

ID: rust/rust-channel-recv-disconnected

Also available as: JSON · Markdown
86%Fix Rate
88%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

The sender side of the channel was dropped while the receiver was still waiting. Handle the disconnected case gracefully.

generic

Workarounds

  1. 90% success Handle RecvError properly instead of unwrapping
    match rx.recv() {
        Ok(msg) => process(msg),
        Err(RecvError) => { /* sender dropped, clean up */ break; }
    }

    Sources: https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html

  2. 85% success Use recv_timeout or try_recv for non-blocking patterns
    use std::time::Duration;
    match rx.recv_timeout(Duration::from_secs(5)) {
        Ok(msg) => process(msg),
        Err(RecvTimeoutError::Timeout) => continue,
        Err(RecvTimeoutError::Disconnected) => break,
    }

    Sources: https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html#method.recv_timeout

Dead Ends

Common approaches that don't work:

  1. Keep the sender alive with a leaked reference to prevent drop 85% fail

    Memory leak and the sender will never send meaningful data; just delays the problem

Error Chain

Leads to:
Preceded by:
Frequently confused with: