Go错误处理的基本规则有哪些

2024-03-14

这篇文章主要讲解了“Go错误处理的基本规则有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Go错误处理的基本规则有哪些”吧!

规则1-不要忽略错误

迟早你的函数将返回失败,你将花费大量时间来确定原因并恢复程序。

处理这些错误。如果您很急或太累-那么休息一下。

package main

import (
"fmt"
"time"
)

func main() {
// 不要忽略这里的错误
lucky, _ := ifItCanFailItWill()
}

func ifItCanFailItWill() (string, error) {
nowNs := time.Now().Nanosecond()
if nowNs % 2 == 0 {
return "shinny desired value", nil
}

return "", fmt.Errorf("I will fail one day, handle me")
}

规则2

尽早返回错误

首先专注于代码执行的“happy path”可能很自然,但是我更喜欢从验证开始,并在最后一切都100%完好时才返回值。

缩放性差:

func nah() (string, error) {
nowNs := time.Now().Nanosecond()
if nowNs % 2 == 0 && isValid() {
return "shinny desired value", nil
}

return "", fmt.Errorf("I will fail one day, handle me")
}

更专业的:

func earlyReturnRocks() (string, error) {
nowNs := time.Now().Nanosecond()
if nowNs % 2 > 0 {
return "", fmt.Errorf("time dividability must be OCD compliant")
}

if !isValid() {
return "", fmt.Errorf("a different custom, specific, helpful error message")
}

return "shinny desired value", nil
}

优点?

  • 更容易阅读

  • 轻松添加更多验证

  • 嵌套代码更少(尤其是在循环中)

  • 明确关注安全和错误处理

  • 每个if条件可能有特定的错误消息

规则3

返回值或错误(但不能同时包含两者)

我看到开发人员同时使用返回值和错误。这是一个坏习惯。避免这样做。

令人困惑:

func validateToken() (desiredValue string, expiredAt int, err error) {
nowNs := time.Now().Nanosecond()
if nowNs % 2 > 0 {
// THE expiredAt (nowNs) SHOULD NOT BE RETURNED TOGETHER WITH THE ERR
return "", nowNs, fmt.Errorf("token expired")
}

return "shinny desired value", 0, nil
}

不足?

  • 方法签名不清楚

  • 必须对方法进行反向工程,以了解返回的值以及何时返回

没错,有时您需要返回有关该错误的其他信息,在这种情况下,请创建一个新的专用Error对象。

更专业的:

package main

import (
"fmt"
"github.com/davecgh/go-spew/spew"
"time"
)

func main() {
value, err := validateToken()
if err != nil {
spew.Dump(err.Error())
}

spew.Dump(value)
}

// Compatible with error built-in interface.
//
// type error interface {
// Error() string
// }
type TokenExpiredErr struct {
expiredAt int
}

func (e TokenExpiredErr) Error() string {
return fmt.Sprintf("token expired at block %d", e.expiredAt)
}

func validateToken() (desiredValue string, err error) {
nowNs := time.Now().Nanosecond()
if nowNs % 2 > 0 {
return "", TokenExpiredErr{expiredAt: nowNs}
}

return "shinny desired value", nil
}

规则4

记日志或返回(但不能同时)

当你将错误写入log时,就是在处理它。不要将错误返回给呼叫者迫使他处理!

为什么?因为您不想两次或多次对同一条消息记录日志:

package main

import (
"fmt"
"os"
"time"
)

func main() {
// validateToken() is already doing the logging,
// but I didn't reverse engineer the method so I don't know about that
// and now I will unfortunately end up with the same message being logged twice
_, err := validateToken()
if err != nil {
// I have nowhere to return it, SO I RIGHTFULLY LOG IT
// And I will not ignore a possible error writing err
_, err = fmt.Fprint(os.Stderr, fmt.Errorf("validating token failed. %s", err.Error()))
if err != nil {
// Extremely rare, no other choice
panic(err)
}

os.Exit(1)
}
}

type TokenExpiredErr struct {
expiredAt int
}

func (e TokenExpiredErr) Error() string {
return fmt.Sprintf("token expired at block %d", e.expiredAt)
}

func validateToken() (desiredValue string, err error) {
nowNs := time.Now().Nanosecond()
if nowNs % 2 > 0 {
// DO NOT LOG AND RETURN
// DO NOT LOG AND RETURN
// DO NOT LOG AND RETURN
fmt.Printf("token validation failed. token expired at %d", nowNs)
return "", TokenExpiredErr{expiredAt: nowNs}
}

return "shinny desired value", nil
}

即用日志记录,又返回错误会导致混乱输出:

token validation failed. token expired at 115431493validating token failed. token expired at block 115431493

更专业的:log或返回错误,选其一:

validating token failed. token expired at block 599480733

规则5

在IDE中将if err != nil配置为宏

感谢各位的阅读,以上就是“Go错误处理的基本规则有哪些”的内容了,经过本文的学习后,相信大家对Go错误处理的基本规则有哪些这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是本站,小编将为大家推送更多相关知识点的文章,欢迎关注!

《Go错误处理的基本规则有哪些.doc》

下载本文的Word格式文档,以方便收藏与打印。