Skip to main content

nb_api/
error.rs

1//! Structured error types for `nb-api`.
2//!
3//! This module hosts [`NbError`] and its associated types
4//! ([`ParseErrorKind`], [`IoError`], [`IoErrorKind`]) as defined by
5//! the `add-note-document-model` (P1) specification. All variants
6//! derive `Serialize`/`Deserialize` so errors round-trip cleanly
7//! through JSON-encoded wire protocols (MCP tool responses, etc.).
8//!
9//! [`NbError`] also derives `Display` and implements
10//! [`std::error::Error`], so existing textual error reporting paths
11//! continue to work unchanged.
12//!
13//! # Migration (from `nb-api` 0.2.x to 0.3.0)
14//!
15//! | Old variant | New variant | Migration |
16//! |---|---|---|
17//! | `CommandFailed(String)` | `CommandFailed { command, stderr, exit_code }` | capture fields at call sites; map validation/policy failures to `ValidationError` |
18//! | `NotFound` (unit) | `ExecutableNotFound { path }` | the unit means `nb` binary missing; track path |
19//! | `Io(std::io::Error)` | `Io { path, source: IoError }` | track path in callers; convert via `From`; reverse is lossy |
20//! | `UnsupportedShowTarget { selector, actual_type }` | Same | Unchanged |
21//! | `DuplicateTitleHeading { title, heading }` | Same | Unchanged |
22//!
23//! New variants introduced in 0.3.0: `ParseError`, `InvalidFingerprint`,
24//! `JsonParseError`, `ValidationError`, `ExecutableNotFound`,
25//! `UnsupportedDocumentFormat`.
26//!
27//! ## New `UnsupportedDocumentFormat` variant (R3 revision)
28//!
29//! This is a NEW variant. There is no `nb-api 0.2.x` predecessor.
30//! Consumers upgrading to `nb-api 0.3.0` SHALL add the variant to
31//! their match arms. **Adding a variant to an exhaustive enum
32//! match produces a compile error, not a warning; wildcard
33//! matches continue compiling.** The constant
34//! [`SUPPORTED_DOCUMENT_EXTENSIONS`] (crate-root re-export of the
35//! source-of-truth declared in `parser`) is the basis for the
36//! `supported` payload at construction time.
37
38use std::error::Error as _; // `.source()` on `std::io::Error`
39use std::path::PathBuf;
40
41use serde::{Deserialize, Serialize};
42
43/// Errors raised by `nb-api` operations.
44///
45/// All variants are serializable so they can traverse MCP tool
46/// response envelopes without lossy string flattening. The
47/// [`std::error::Error`] implementation remains for ergonomic
48/// interop with code that uses `?` and standard error reporting.
49///
50/// `std::error::Error` is implemented MANUALLY below rather than
51/// via `thiserror::Error` derive. The derive's autodetect
52/// treats any field named `source` as a `#[source]` chain link
53/// and tries to convert it to `dyn Error`, which fails for
54/// fields of type `String` (e.g., `JsonParseError { source:
55/// String }` per the P1 specification). The manual impl
56/// preserves the field name and only sets a source-chain link
57/// for variants whose source field is itself an `Error`.
58#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
59#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
60#[serde(tag = "type", rename_all = "snake_case")]
61pub enum NbError {
62    /// An `nb` subprocess invocation failed (non-zero exit, or
63    /// spawning failed for a non-NotFound reason).
64    CommandFailed {
65        /// The argument vector (joined) that was executed.
66        command: String,
67        /// Captured stderr (or stdout when stderr was empty).
68        stderr: String,
69        /// Process exit code, if the process started.
70        exit_code: Option<i32>,
71    },
72
73    /// The `nb` executable could not be located on `PATH` (or in
74    /// the resolved location) when a subprocess was spawned.
75    ExecutableNotFound {
76        /// The resolved path the spawn attempt targeted.
77        path: String,
78    },
79
80    /// `nb` reported that the requested selector was not found.
81    NotFound {
82        /// The selector that was not resolved.
83        selector: String,
84    },
85
86    /// An I/O error occurred while accessing a notebook file or
87    /// the on-disk notebook directory. The `source` field captures
88    /// the original `std::io::Error` chain as a serializable
89    /// snapshot (recursive [`IoError`]).
90    Io {
91        /// Path that triggered the I/O error.
92        path: PathBuf,
93        /// Snapshot of the `std::io::Error` chain.
94        source: IoError,
95    },
96
97    /// `nb show` was invoked on a selector whose type is not
98    /// classified as text by `nb` itself (per the
99    /// `add-0-2-0-foundation` public-API spec). Folders, archives,
100    /// audio, video, image, and any other non-textual type reach
101    /// this path. The classification delegates to
102    /// `nb show <selector> --type text` so forward compatibility
103    /// is automatic when `nb` adds new textual types. Probe
104    /// failure (e.g., selector not found) does NOT route here;
105    /// it falls through to the original `CommandFailed` error
106    /// from the content-read path.
107    UnsupportedShowTarget {
108        selector: String,
109        actual_type: String,
110    },
111
112    /// `nb add` was called with a `title` and `content` where the
113    /// first nonblank line of `content` is an exact Markdown ATX H1
114    /// duplicating the title. The validation runs in the caller
115    /// process before any subprocess invocation or notebook side
116    /// effect (including `resolve_notebook`); the rejection
117    /// happens entirely in-process. `heading` carries the exact
118    /// detected source line (including the leading `#` and any
119    /// surrounding whitespace) for actionable diagnostics. See
120    /// `add-0-2-0-foundation` public-API specification.
121    DuplicateTitleHeading { title: String, heading: String },
122
123    /// A structural parse failure.
124    ParseError {
125        kind: ParseErrorKind,
126        location: std::ops::Range<usize>,
127    },
128
129    /// A fingerprint string failed structural validation (wrong
130    /// prefix, wrong length, mixed case, etc.). `reason` carries a
131    /// machine-readable category (e.g., `"empty"`,
132    /// `"unknown_algorithm_prefix"`, `"uppercase_hex"`).
133    InvalidFingerprint { reason: String },
134
135    /// JSON deserialization failed when constructing a typed
136    /// wrapper (e.g., [`crate::fingerprint::Fingerprint::from_json`]).
137    JsonParseError {
138        // Field is named `source` per the P1 specification.
139        source: String,
140    },
141
142    /// A semantic validation error raised by an operation boundary
143    /// (e.g., rejecting input that is structurally valid but
144    /// semantically illegal). `location` is `None` when the
145    /// failure is not byte-anchored.
146    ValidationError {
147        reason: String,
148        location: Option<std::ops::Range<usize>>,
149    },
150
151    /// Format-dispatch refusal (R3 revision).
152    ///
153    /// `parse(bytes, FromPath(path))` returned this error because
154    /// the final filename matched one of the recognized-but-
155    /// unsupported dotted suffixes (e.g., `.org`, `.latex`,
156    /// `.tex`, `.adoc`, `.asciidoc`). Format dispatch precedes
157    /// byte parsing, so no bytes were consumed and no
158    /// parse-error location is meaningful — this is a
159    /// contextual configuration error, not a parse failure.
160    ///
161    /// `extension` carries the lowercase dotted suffix WITHOUT
162    /// the leading dot (e.g., `"org"`, `"latex"`).
163    /// `supported` is the owned canonical list of supported
164    /// extensions, populated at construction time from
165    /// `crate::SUPPORTED_DOCUMENT_EXTENSIONS`. The owned
166    /// `Vec<String>` shape is required for the derived
167    /// `Serialize` / `Deserialize` round-trip contract on
168    /// `NbError`.
169    UnsupportedDocumentFormat {
170        extension: String,
171        supported: Vec<String>,
172    },
173
174    /// Process-shared gate queue wait exceeded. Notebook was not mutated.
175    GateTimeout { gate: String, timeout_ms: u64 },
176
177    /// `Transaction::commit` refused because the notebook worktree/index is dirty.
178    DirtyBaseline { guidance: String },
179
180    /// Plan-op path collision against snapshot or earlier plan ops.
181    PathCollision {
182        path: String,
183        plan_index: Option<u32>,
184    },
185
186    /// Plan targets or would leave durable state on a Git-ignored path in a
187    /// way that cannot be represented in the single checkpoint (existing
188    /// ignored entry mutation), or requires force-staging (reported only when
189    /// force-stage is unavailable). Prefer rejecting existing-ignored mutators.
190    PathIgnored {
191        path: String,
192        guidance: String,
193        plan_index: Option<u32>,
194    },
195
196    /// Validation/apply failure tied to a plan entry.
197    PlanValidation {
198        kind: String,
199        message: String,
200        plan_index: Option<u32>,
201    },
202
203    /// Commit completion is unknown (e.g. transport timeout after checkpoint may have started).
204    IndeterminateCommit {
205        pre_revision: String,
206        post_revision_observed: Option<String>,
207        guidance: String,
208    },
209
210    /// Cleanup after a known failed apply could not verify clean `pre_revision`.
211    RecoveryRequired {
212        pre_revision: String,
213        post_revision_observed: Option<String>,
214        status_observed: Option<String>,
215        preserved_paths: Option<Vec<String>>,
216        guidance: String,
217    },
218
219    /// Body fingerprint precondition failed.
220    FingerprintMismatch {
221        target: crate::types::NoteTarget,
222        guidance: String,
223    },
224
225    /// Line number/anchor precondition failed.
226    AnchorMismatch {
227        target: String,
228        number: u32,
229        guidance: String,
230    },
231
232    /// Substring `expected_count` did not match actual matches.
233    OccurrenceMismatch { expected: u32, actual: u32 },
234
235    /// Overlapping line edits in one batch.
236    OverlappingEdits { indices: Vec<u32> },
237
238    /// Invalid `show_note_lines` window.
239    InvalidLineWindow {
240        offset: u32,
241        limit: u32,
242        total_lines: u32,
243    },
244
245    /// Empty substring pattern refused at enqueue/apply.
246    EmptySubstringPattern,
247
248    /// Contiguous-body-only op invoked on a multi-fragment document.
249    FragmentedBody {
250        fragment_count: u32,
251        guidance: String,
252    },
253
254    /// Structured text surface hit non-UTF-8 bytes in a text-classified file.
255    ///
256    /// Non-textual notes keep using `UnsupportedShowTarget`; this variant
257    /// covers the narrow non-UTF-8-but-text case. Use
258    /// `NbClient::read_note_source_bytes` for raw access.
259    NonUtf8 {
260        selector: String,
261        path: String,
262        kind: String,
263        #[serde(default, skip_serializing_if = "Option::is_none")]
264        mime_hint: Option<String>,
265    },
266
267    /// `.nb-api-index.lock` wait exceeded before any mutation.
268    IndexLockTimeout { path: String, timeout_ms: u64 },
269
270    /// Document structure is not supported for the requested op.
271    UnsupportedStructure { reason: String },
272}
273
274impl std::fmt::Display for NbError {
275    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276        match self {
277            Self::CommandFailed {
278                command,
279                stderr,
280                exit_code,
281            } => write!(
282                f,
283                "command {command:?} failed (exit {exit_code:?}): {stderr}"
284            ),
285            Self::ExecutableNotFound { path } => {
286                write!(f, "`nb` executable not found at path {path:?}")
287            },
288            Self::NotFound { selector } => {
289                write!(f, "not found: {selector:?}")
290            },
291            Self::Io { path, source } => {
292                write!(f, "I/O error at {path:?}: {source}")
293            },
294            Self::UnsupportedShowTarget {
295                selector,
296                actual_type,
297            } => write!(
298                f,
299                "selector `{selector}` resolved to non-textual type `{actual_type}`; \
300                 `nb show` does not display non-textual content"
301            ),
302            Self::DuplicateTitleHeading { title, heading } => write!(
303                f,
304                "title `{title}` duplicates the first H1 in content (`{heading}`); \
305                 remove the duplicate heading to avoid double-rendering"
306            ),
307            Self::ParseError { kind, location } => {
308                write!(f, "parse error: {kind:?} at {location:?}")
309            },
310            Self::InvalidFingerprint { reason } => {
311                write!(f, "invalid fingerprint: {reason:?}")
312            },
313            Self::JsonParseError { source } => {
314                write!(f, "JSON parse error: {source:?}")
315            },
316            Self::ValidationError {
317                reason,
318                location: _,
319            } => {
320                write!(f, "validation error: {reason:?}")
321            },
322            Self::UnsupportedDocumentFormat {
323                extension,
324                supported,
325            } => {
326                write!(
327                    f,
328                    "unsupported document format: {extension:?} (supported: {supported:?})"
329                )
330            },
331            Self::GateTimeout { gate, timeout_ms } => {
332                write!(
333                    f,
334                    "gate timeout waiting on {gate} after {timeout_ms}ms"
335                )
336            },
337            Self::DirtyBaseline { guidance } => {
338                write!(f, "dirty baseline: {guidance}")
339            },
340            Self::PathCollision { path, plan_index } => {
341                write!(
342                    f,
343                    "path collision at {path:?} (plan_index={plan_index:?})"
344                )
345            },
346            Self::PathIgnored {
347                path,
348                guidance,
349                plan_index,
350            } => write!(
351                f,
352                "ignored path {path:?} (plan_index={plan_index:?}): {guidance}"
353            ),
354            Self::PlanValidation {
355                kind,
356                message,
357                plan_index,
358            } => write!(
359                f,
360                "plan validation ({kind}) at index {plan_index:?}: {message}"
361            ),
362            Self::IndeterminateCommit {
363                pre_revision,
364                post_revision_observed,
365                guidance,
366            } => write!(
367                f,
368                "indeterminate commit (pre={pre_revision}, post={post_revision_observed:?}): {guidance}"
369            ),
370            Self::RecoveryRequired {
371                pre_revision,
372                guidance,
373                ..
374            } => write!(
375                f,
376                "recovery required (pre_revision={pre_revision}): {guidance}"
377            ),
378            Self::FingerprintMismatch { target, guidance } => {
379                write!(f, "fingerprint mismatch for {target:?}: {guidance}")
380            },
381            Self::AnchorMismatch {
382                target,
383                number,
384                guidance,
385            } => write!(
386                f,
387                "anchor mismatch for {target} line {number}: {guidance}"
388            ),
389            Self::OccurrenceMismatch { expected, actual } => {
390                write!(
391                    f,
392                    "occurrence mismatch: expected={expected} actual={actual}"
393                )
394            },
395            Self::OverlappingEdits { indices } => {
396                write!(f, "overlapping edits at indices {indices:?}")
397            },
398            Self::InvalidLineWindow {
399                offset,
400                limit,
401                total_lines,
402            } => write!(
403                f,
404                "invalid line window offset={offset} limit={limit} total_lines={total_lines}"
405            ),
406            Self::EmptySubstringPattern => {
407                write!(f, "empty substring pattern")
408            },
409            Self::FragmentedBody {
410                fragment_count,
411                guidance,
412            } => write!(
413                f,
414                "fragmented body ({fragment_count} fragments): {guidance}"
415            ),
416            Self::NonUtf8 {
417                selector,
418                path,
419                kind,
420                mime_hint,
421            } => write!(
422                f,
423                "non-UTF-8 text at {selector:?} ({path:?}, kind={kind}, mime={mime_hint:?}); use read_note_source_bytes for raw access"
424            ),
425            Self::IndexLockTimeout { path, timeout_ms } => {
426                write!(f, "index lock timeout on {path} after {timeout_ms}ms")
427            },
428            Self::UnsupportedStructure { reason } => {
429                write!(f, "unsupported structure: {reason}")
430            },
431        }
432    }
433}
434
435impl std::error::Error for NbError {
436    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
437        // Only `Io { source: IoError }` carries a true source-chain
438        // link. Every other variant's `source` field (where
439        // present) is a diagnostic String or a non-Error type, so
440        // we explicitly return `None` for them.
441        match self {
442            Self::Io { source, .. } => Some(source),
443            _ => None,
444        }
445    }
446}
447
448/// Narrow refusal contract for the structural parser.
449///
450/// `parse` accepts every input that can be losslessly partitioned
451/// into a [`crate::parser::NoteDocument`], including the frozen
452/// W1 and E1-E11 noncanonical forms. The ONLY refusal cases at
453/// the parse layer are:
454///
455/// - Todo with no non-blank line at all: [`ParseErrorKind::MissingTitle`].
456/// - Bookmark with no non-blank line at all: [`ParseErrorKind::MissingTitle`].
457///
458/// Notes are permissive on empty source. Title-shape errors belong
459/// to a later strict validator (P5+), not to the parser.
460#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
461#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
462pub enum ParseErrorKind {
463    /// The first non-blank line was missing entirely (Todo/Bookmark
464    /// only; Notes are permissive).
465    MissingTitle,
466}
467
468/// Serializable snapshot of a [`std::io::Error`] chain.
469///
470/// `IoError` captures the **chain structure** (as a tree of
471/// snapshots) but does NOT preserve the original `std::io::Error`
472/// identity. The forward conversion [`From<std::io::Error>`] walks
473/// [`std::error::Error::source`] and recurses for each
474/// `std::io::Error` link; nested non-`io::Error` sources are
475/// stringified into [`IoErrorKind::Other`].
476///
477/// The reverse conversion [`From<IoError>`] for `std::io::Error`
478/// is **explicitly lossy** — see [`IoError`]'s `From` impl.
479#[derive(
480    Debug, Clone, Serialize, Deserialize, PartialEq, Eq, thiserror::Error,
481)]
482#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
483#[error("{kind:?}: {message}")]
484pub struct IoError {
485    pub kind: IoErrorKind,
486    pub message: String,
487    pub os_error: Option<i32>,
488    pub source: Option<Box<IoError>>,
489}
490
491/// Discriminator for the `std::io::ErrorKind` taxonomy, lifted into
492/// a serializable form. Marked `#[non_exhaustive]` so future
493/// versions can add new kinds without breaking downstream
494/// `match` arms that include a default branch.
495#[non_exhaustive]
496#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
497#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
498pub enum IoErrorKind {
499    NotFound,
500    PermissionDenied,
501    ConnectionRefused,
502    ConnectionReset,
503    ConnectionAborted,
504    NotConnected,
505    AddrInUse,
506    AddrNotAvailable,
507    BrokenPipe,
508    AlreadyExists,
509    WouldBlock,
510    InvalidInput,
511    InvalidData,
512    TimedOut,
513    WriteZero,
514    Interrupted,
515    UnexpectedEof,
516    OutOfMemory,
517    /// Catch-all for nested sources that are not themselves
518    /// `std::io::Error` (e.g., a third-party crate's error type
519    /// captured as `source`).
520    Other,
521}
522
523impl IoErrorKind {
524    /// Map a `std::io::ErrorKind` into the serializable variant.
525    pub fn from_std(kind: std::io::ErrorKind) -> Self {
526        match kind {
527            std::io::ErrorKind::NotFound => Self::NotFound,
528            std::io::ErrorKind::PermissionDenied => Self::PermissionDenied,
529            std::io::ErrorKind::ConnectionRefused => Self::ConnectionRefused,
530            std::io::ErrorKind::ConnectionReset => Self::ConnectionReset,
531            std::io::ErrorKind::ConnectionAborted => Self::ConnectionAborted,
532            std::io::ErrorKind::NotConnected => Self::NotConnected,
533            std::io::ErrorKind::AddrInUse => Self::AddrInUse,
534            std::io::ErrorKind::AddrNotAvailable => Self::AddrNotAvailable,
535            std::io::ErrorKind::BrokenPipe => Self::BrokenPipe,
536            std::io::ErrorKind::AlreadyExists => Self::AlreadyExists,
537            std::io::ErrorKind::WouldBlock => Self::WouldBlock,
538            std::io::ErrorKind::InvalidInput => Self::InvalidInput,
539            std::io::ErrorKind::InvalidData => Self::InvalidData,
540            std::io::ErrorKind::TimedOut => Self::TimedOut,
541            std::io::ErrorKind::WriteZero => Self::WriteZero,
542            std::io::ErrorKind::Interrupted => Self::Interrupted,
543            std::io::ErrorKind::UnexpectedEof => Self::UnexpectedEof,
544            std::io::ErrorKind::OutOfMemory => Self::OutOfMemory,
545            _ => Self::Other,
546        }
547    }
548}
549
550impl From<std::io::ErrorKind> for IoErrorKind {
551    fn from(kind: std::io::ErrorKind) -> Self {
552        Self::from_std(kind)
553    }
554}
555
556impl From<std::io::Error> for IoError {
557    /// Capture an `io::Error` chain as a tree of serializable
558    /// snapshots.
559    ///
560    /// The implementation recursively walks the
561    /// [`std::error::Error::source`] chain on BORROWED
562    /// `&dyn Error` references. This is critical: `std::io::Error`
563    /// is not `Clone`, so we cannot reconstruct an inner error
564    /// from a borrow without losing its `raw_os_error()` and its
565    /// own source chain. Walking the borrow preserves the chain
566    /// STRUCTURE exactly.
567    ///
568    /// At each level: if the source is itself an `io::Error`,
569    /// recurse on its borrow; otherwise, capture the source as
570    /// an [`IoErrorKind::Other`] snapshot (preserving the
571    /// `Display` text and walking its own source chain for
572    /// nested non-io links).
573    fn from(err: std::io::Error) -> Self {
574        snapshot_io_error(err)
575    }
576}
577
578/// Build an `IoError` snapshot from an `io::Error` value, then
579/// walk its source chain via the borrowed `dyn Error` to
580/// preserve chain structure exactly.
581fn snapshot_io_error(err: std::io::Error) -> IoError {
582    let kind = IoErrorKind::from_std(err.kind());
583    let os_error = err.raw_os_error();
584    let message = err.to_string();
585    let source = walk_source_chain(err.source());
586    IoError {
587        kind,
588        message,
589        os_error,
590        source,
591    }
592}
593
594/// Walk a `&(dyn Error + 'static)` chain, building a list of
595/// `IoError` snapshots. Each link appears EXACTLY ONCE in the
596/// chain (no duplication). Each `std::io::Error` link has its
597/// `raw_os_error()` preserved verbatim via the recursive walk
598/// on the borrowed `dyn Error`.
599///
600/// The chain is built by snapshotting the CURRENT node with its
601/// `source` field set to the recursive walk of the NEXT node.
602/// This avoids the A→B→B duplication that would arise from both
603/// recursing into the source AND iterating/appending the same
604/// source.
605fn walk_source_chain(
606    source: Option<&(dyn std::error::Error + 'static)>,
607) -> Option<Box<IoError>> {
608    let head = source?;
609    Some(Box::new(snapshot_link(head)))
610}
611
612/// Snapshot a single link in the source chain. The link's `source`
613/// field is set to the recursive snapshot of the next link.
614fn snapshot_link(current: &(dyn std::error::Error + 'static)) -> IoError {
615    if let Some(io_err) = current.downcast_ref::<std::io::Error>() {
616        IoError {
617            kind: IoErrorKind::from_std(io_err.kind()),
618            message: io_err.to_string(),
619            os_error: io_err.raw_os_error(),
620            // The recursive walk captures the io_err's own
621            // chain. Each io_err-level appears exactly once.
622            source: walk_source_chain(io_err.source()),
623        }
624    } else {
625        IoError {
626            kind: IoErrorKind::Other,
627            message: current.to_string(),
628            os_error: None,
629            // Recurse on the next link. Because `walk_source_chain`
630            // snapshots its OWN first link and recurses, the
631            // outer iteration does NOT see the next link — no
632            // duplication.
633            source: walk_source_chain(current.source()),
634        }
635    }
636}
637
638impl From<IoError> for std::io::Error {
639    /// Reverse conversion is **explicitly lossy**.
640    ///
641    /// The implementation prefers [`std::io::Error::from_raw_os_error`]
642    /// when [`IoError::os_error`] is `Some`, which LOSES the
643    /// snapshot message and any source chain. Otherwise, it
644    /// constructs a new `io::Error::new(kind, message)`, which
645    /// loses `raw_os_error()`.
646    ///
647    /// The forward conversion ([`From<std::io::Error>`] for
648    /// `IoError`) preserves chain STRUCTURE; this reverse
649    /// conversion does not — the snapshot tree is collapsed to a
650    /// single `std::io::Error`.
651    fn from(snapshot: IoError) -> Self {
652        if let Some(code) = snapshot.os_error {
653            std::io::Error::from_raw_os_error(code)
654        } else {
655            let kind = match snapshot.kind {
656                IoErrorKind::NotFound => std::io::ErrorKind::NotFound,
657                IoErrorKind::PermissionDenied => {
658                    std::io::ErrorKind::PermissionDenied
659                },
660                IoErrorKind::ConnectionRefused => {
661                    std::io::ErrorKind::ConnectionRefused
662                },
663                IoErrorKind::ConnectionReset => {
664                    std::io::ErrorKind::ConnectionReset
665                },
666                IoErrorKind::ConnectionAborted => {
667                    std::io::ErrorKind::ConnectionAborted
668                },
669                IoErrorKind::NotConnected => std::io::ErrorKind::NotConnected,
670                IoErrorKind::AddrInUse => std::io::ErrorKind::AddrInUse,
671                IoErrorKind::AddrNotAvailable => {
672                    std::io::ErrorKind::AddrNotAvailable
673                },
674                IoErrorKind::BrokenPipe => std::io::ErrorKind::BrokenPipe,
675                IoErrorKind::AlreadyExists => {
676                    std::io::ErrorKind::AlreadyExists
677                },
678                IoErrorKind::WouldBlock => std::io::ErrorKind::WouldBlock,
679                IoErrorKind::InvalidInput => std::io::ErrorKind::InvalidInput,
680                IoErrorKind::InvalidData => std::io::ErrorKind::InvalidData,
681                IoErrorKind::TimedOut => std::io::ErrorKind::TimedOut,
682                IoErrorKind::WriteZero => std::io::ErrorKind::WriteZero,
683                IoErrorKind::Interrupted => std::io::ErrorKind::Interrupted,
684                IoErrorKind::UnexpectedEof => {
685                    std::io::ErrorKind::UnexpectedEof
686                },
687                IoErrorKind::OutOfMemory => std::io::ErrorKind::OutOfMemory,
688                IoErrorKind::Other => std::io::ErrorKind::Other,
689            };
690            std::io::Error::new(kind, snapshot.message)
691        }
692    }
693}