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

use*_*963 0 go

如何在 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)
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*its 5

您可以通过创建自己的实现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)
}
Run Code Online (Sandbox Code Playgroud)

操场上试试。