第 10 章 错误处理 错误处理
本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com
什么错误会让我们的眼睛和耳朵出错?
威廉-莎士比亚(通过锡拉库扎的安提福勒斯之口),《错误的喜剧
错误是生活的一部分。 采用测试驱动开发的原因之一就是确保我们能在安全的情况下尽可能快地开发,将代码中的错误降到最低。
我们功能列表上的下一个项目就是改进错误处理:
5 美元 × 2 = 10 美元 |
10 欧元 × 2 = 20 欧元 |
4002 韩元 / 4 = 1000.5 韩元 |
5 美元 + 10 美元 = 15 美元 |
将测试代码与生产代码分开 |
删除多余的测试 |
5 美元 + 10 欧元 = 17 美元 |
1 美元 + 1100 克鲁瓦 = 2200 克鲁瓦#。 |
根据涉及的货币确定汇率(从→到) |
改进汇率未指定时的错误处理 |
允许修改汇率 |
错误愿望列表
我们的代码目前处理汇率缺失的方式存在缺陷。让我们来解决这个缺陷。 表 10-1列出了我们处理因汇率缺失而导致的错误的愿望清单。
| 项目 | 说明 |
|---|---|
1 |
当缺少一个或多个必要的汇率时, |
2 |
错误信息应该是 "贪婪的"--也就是说,它应该指出所有导致 |
3 |
为防止错误被调用者忽略,当汇率缺失导致错误时,不应返回有效的 |
例如,如果我们尝试评估货币 "Kalganid "的投资组合1的投资组合时,我们应该得到一条详细的错误信息,列出所有缺失的汇率。
Go
当汇率缺失时,我们需要修改convert 和Evaluate 方法的签名。 目前,这些方法只返回一个值。为了显示错误(无法找到汇率),我们需要第二个返回值。
提示
在 Go 中,表示失败的惯用方法是返回一个error 作为函数或方法的最后一个返回值,以便调用者可以检查。
下面是Evaluate 和convert 如何使用 Go 的习语协同工作的伪代码:
Evaluate:
For each Money struct:
Try to convert Money to target currency and add it to the total amount
If convert returns an error:
Capture the "from" and "to" currencies in "failures"
If there are no failures:
Return a Money struct with the total amount and target currency;
return nil for error
Otherwise:
Return an empty Money struct; return an error message
including all the failures
有了这些伪代码,让我们在money_test.go 中编写一个失败的测试。该测试与现有测试略有不同:它期望返回错误,并将错误信息与预期信息进行比较:
funcTestAdditionWithMultipleMissingExchangeRates(t*testing.T){varportfolios.PortfoliooneDollar ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access