尽管在Go中处理错误异常烦人,但我更喜欢显式错误检查,而不是将异常抛出并希望有人抓住它。我正在看着你哦,Java!
这是我在Go中处理错误的5条规则。
迟早你的函数将返回失败,你将花费大量时间来确定原因并恢复程序。
处理这些错误。如果您很急或太累-那么休息一下。
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") }
首先专注于代码执行的“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 }
优点?
我看到开发人员同时使用返回值和错误。这是一个坏习惯。避免这样做。
令人困惑:
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 }
当你将错误写入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
if err != nil
配置为宏我无法继续输入错误检查信息,因此我创建了一个快速视频指南,该指南介绍了如何在Intellij的GoLand中进行设置。我将宏绑定到了Mouse 4按钮上,该按钮通常用于在《激战2》中治愈我的死灵法师:)
goland宏配置视频指南
本文翻译自[《How to handle errors in Go? 5 rules》(https://web3.coach/golang-how-to-handle-errors-five-rules)]。
讲师主页:tonybai_cn
讲师博客: Tony Bai
实战课:《Kubernetes实战:高可用集群搭建,配置,运维与应用》
免费课:《Kubernetes基础:开启云原生之门》
讲师公众号:iamtonybai(或扫描下方二维码)