Skip to content

Commit

Permalink
add #66
Browse files Browse the repository at this point in the history
  • Loading branch information
smallnest committed Apr 21, 2024
1 parent 88944c0 commit 96b70d1
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ Go tips from [Phuong Le](https://twitter.com/func25).
| 63 | | |
| 64 | | |
| 65 | Returning Pointers Made Easy with Generics | miniLCT |
| 66 | | |
| 66 | Simplify Your Error Messages in fmt.Errorf | smallnest |
| 67 | How to deal with long function signatures | richzw |
| 68 | Use the deadcode tool to find and remove unused functions | richzw |
| 69 | Manage multiple goroutines with errgroup | richzw |
Expand Down
33 changes: 33 additions & 0 deletions src/066.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Tip #66 在fmt.Errorf中简化你的错误信息

> 原始链接:[Golang Tip #66: Simplify Your Error Messages in fmt.Errorf](https://twitter.com/func25/status/1775481695594291238)
>
在Go语言中,当我们处理错误时,提供足够的详细信息以便了解问题的具体原因是非常重要的。

之前有一个提示,即 Go Tips#38,专门讨论了这个问题。我们可以通过访问以下链接获取更多上下文信息:[tips#38](https://colobu.com/gotips/038.html)

(感谢 `@thedenisnikulin` 提供的额外建议,我们可以进一步改进错误处理方式。)

现在,我们应该熟悉使用 `fmt.Errorf` 函数以及 `%w` 来包裹(wrap)错误的做法:

![](./images/066/1.jpeg)

通常情况下,我们可能会得到一个像这样的长错误消息:

"error while crawling: can't retrieve log: failed to open file server-logs.txt: file not exist.""

这个消息虽然清晰,但比实际所需冗长,因为它重复了一些诸如“error while”、“failed to”这样的短语,而我们知道我们在处理错误时,这些前置词汇是可以省略的。

因此,这里有一种更好的做法:

![](./images/066/2.jpeg)

注意到不同之处了吗?

相比于冗长的消息,我们得到的是更简洁、更直接的内容:
"crawling: retrieve log: open file server-logs.txt: file not exist.""

这条消息仍然清楚地告诉你错误发生时正在进行的操作,并且更容易阅读。

因此,在Go语言中编写错误消息时,要保持简短,重点突出未能成功执行的动作。
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
- [Tip #47 表驱动测试,测试集和并行运行测试](./047.md)
- [Tip #71 用泛型让 sync.Pool 类型安全](./071.md)
- [Tip #65 使用泛型返回指针](./065.md)
- [Tip #66 在fmt.Errorf中简化你的错误信息](./066.md)
- [Tip #67 如何处理长函数签名](./067.md)
- [Tip #68 使用deadcode工具来找到和删除无用的函数](./068.md)
- [Tip #69 通过errgrup管理多个goroutine](./069.md)
Expand Down
Binary file added src/images/066/1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/images/066/2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 96b70d1

Please sign in to comment.