1 回答
TA贡献1842条经验 获得超12个赞
为此,可以创建自己的实现接口的类型,然后使用错误包装(有关详细信息,请参阅此博客文章)。结果如下:error
package main
import (
"errors"
"fmt"
"os"
"strconv"
)
type fooErr int
func (e fooErr) Error() string { return strconv.Itoa(int(e)) }
func main() {
errCode := 0
_, err := foo()
if err != nil {
var e fooErr
if errors.As(err, &e) {
fmt.Printf("error thrown, exit code: %v", e)
errCode = int(e)
} else {
fmt.Printf("error thrown, dont have a code: %v", err)
errCode = 1 // default code...
}
}
// I can parse the exit code out of err, but that seems wrong...
// how can I exit with the exit code cleanly? do i need to create a custom error that I bubble up and handle?
os.Exit(errCode)
}
func foo() (string, error) {
_, err := bar()
if err != nil {
return "", fmt.Errorf("foo fails b/c bar fails %w", err)
}
return "OK", nil
}
func bar() (string, error) {
exitCode := fooErr(208)
return "", fmt.Errorf("some error happened in bar, exit code: %w", exitCode)
}
在操场上试试吧。
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报