知识卡片

普通读书笔记卡 · 743.d.2.b.7.c · 生成模型:未记录

恢复动作按失败原因触发

理解等级:中级

可恢复失败需要先区分原因。打开文件仅在 NotFound 时适合在原路径尝试创建;权限不足应作为另一种问题处理。补救操作也会失败,要保留其错误信息。除了写内层 match,还能用 unwrap_or_else,只在 Err 时计算回退行为。

相关卡片 [[结果类型承载失败信息]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 错误处理 Recoverable Errors with Result · 查看原书依据

      The condition we want to check in the inner match is whether the value returned by error.kind() is the NotFound variant of the ErrorKind enum. If it is, we try to create the file with File::create. However, because File::create could also fail, we need a second arm in the inner match expression. When the file can’t be created, a different error message is printed.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第09章 错误处理(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c09.xhtml`,块 0060) - 结论依据:原文详细区分打开失败、可尝试创建和创建也失败三种路径。 - 原始内容:The condition we want to check in the inner match is whether the value returned by error.kind() is the NotFound variant of the ErrorKind enum. If it is, we try to create the file with File::create. However, because File::create could also fail, we need a second arm in the inner match expression. When the file can’t be created, a different error message is printed.