如何在终止程序时错误地嵌入退出代码以使用?

如何在 go 错误中嵌入退出代码,将其冒泡,然后在处理错误时使用退出代码退出?


例如:


func main () {

  foo, err := foo()

  if err != nil{

    fmt.Printf("error thrown, exit code: %v", err )

  }

  // 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(1)

}


func foo() (string, err) {

  bar, err := bar()

  if err != nil {

     return "", fmt.Errorf("foo fails b/c bar fails %v": err)

  }

}


func bar() (string, err) {

  exitCode := 208

  return "", fmt.Errorf("some error happened in bar, exit code: %v", exitCode)

}


慕沐林林
浏览 91回答 1
1回答

红颜莎娜

为此,可以创建自己的实现接口的类型,然后使用错误包装(有关详细信息,请参阅此博客文章)。结果如下:errorpackage mainimport (    "errors"    "fmt"    "os"    "strconv")type fooErr intfunc (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)}在操场上试试吧。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go