知识卡片
外部操作错误进入编译诊断
一个过程宏可能调用多个外部 API,而这些调用往往有不同的错误类型。书中把四类 AWS SDK 操作的错误用 From 转换为项目的 IacError,分成建桶、建函数和连接事件三类。远端错误包含消息时保留消息,宏入口再将项目错误交给 syn::Error 生成编译错误 token。
DSL 语法错误可利用输入 token 的 span 精确定位。外部资源写入失败更适合报告宏调用处,并指出失败的动作。本例用 Span::call_site() 和错误类型对应的上下文构造诊断。仅保留 SDK 错误消息是教学代码的简化,若还需按错误种类区分重试条件,就需要保留分类信息。
相关卡片 [[声明宏生成过程宏样板]]、[[宏展开可能触发外部写入]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Writing an infrastructure DSL 把服务错误变成编译诊断 · 查看原书依据
Our custom IacError is an enum with one variant for each kind of error that might occur: creating a bucket or lambda might fail, and setting up the event could go awry. IacError implements Error and has the required Display implementation. It also has a custom method for turning into a TokenStream, which is what we will have to output.
参考来源
- 位置:《Write Powerful Rust Macros》第09章《Writing an infrastructure DSL》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-9.xhtml#p152)
- 结论依据:原文描述 IacError 的三个变体及其输出 token 的职责,清单 9.24 展示如何合并 AWS 错误与宏调用 span。
- 原始内容:Our custom IacError is an enum with one variant for each kind of error that might occur: creating a bucket or lambda might fail, and setting up the event could go awry. IacError implements Error and has the required Display implementation. It also has a custom method for turning into a TokenStream, which is what we will have to output.