gpt4 book ai didi

error-handling - Go 中更简洁的错误处理

转载 作者:IT王子 更新时间:2023-10-29 01:24:57 25 4
gpt4 key购买 nike

我如何处理 Go 中的大量错误?

我查看我的代码,发现它充满了错误处理程序:

err = result.Scan(&bot.BID, &bot.LANGUAGE, &bot.SOURCE)
if err != nil {
log.Fatalf("result.Scan: %v", err)
return
}

fileName, err := copySourceToTemporaryFile(bot)
if err != nil {
log.Fatalf("copySourceToTemporaryFile: %v", err)
return
}
...

很多行看起来像:

// do something
// handle error
// handle error
// handle error

// do something 2
// handle error
// handle error
// handle error

我能否创建一个打印错误并停止处理的默认处理程序,或者至少从我的代码逻辑中移出这个“错误处理程序垃圾”?

最佳答案

这让我想起了最近的 Errors are values Rob Pike 以及 Mr. Rob Pike taught me about practice of error handling in Go at GoCon 2014

The key lesson, however, is that errors are values and the full power of the Go programming language is available for processing them.

It's worth stressing that whatever the design, it's critical that the program check the errors however they are exposed. The discussion here is not about how to avoid checking errors, it's about using the language to handle errors with grace.

一种技术是定义一个名为 errWriter 的对象:

type errWriter struct {
w io.Writer
err error
}

The write method calls the Write method of the underlying Writer and records the first error for future reference:

func (ew *errWriter) write(buf []byte) {
if ew.err != nil {
return
}
_, ew.err = ew.w.Write(buf)
}

As soon as an error occurs, the write method becomes a no-op but the error value is saved.

Given the errWriter type and its write method, the code above can be refactored:

ew := &errWriter{w: fd}
ew.write(p0[a:b])
ew.write(p1[c:d])
ew.write(p2[e:f])
// and so on
if ew.err != nil {
return ew.err
}

关于error-handling - Go 中更简洁的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28409118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com