0

How can I embed an exit code in a go error, bubble it up, and then exit with the exit code when I handle the error?

For example:

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)
}

1 Answer 1

4

You can do this by creating your own type that implements the error interface and then using error wrapping (see this blog post for more info). The result is something like:

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)
}

Try it in the playground.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.