Hacker News new | ask | show | jobs
by hnakamur 3514 days ago
In Go, I use https://github.com/pkg/errors these days and wrap errors with stack trace.

  package main
  
  import (
          "fmt"
          "io"
          "os"
  
          "github.com/pkg/errors"
  )
  
  func main() {
          v, err := run()
          if err != nil {
                  fmt.Printf("err=%+v\n", err)
                  os.Exit(1)
          }
          fmt.Printf("v=%d\n", v)
  }
  
  func run() (*int, error) {
          a, err := foo()
          if err != nil {
                  return nil, errors.WithStack(err)
          }
          b, err := a.bar()
          if err != nil {
                  return nil, errors.WithStack(err)
          }
          c, err := b.baz()
          if err != nil {
                  return nil, errors.WithStack(err)
          }
          return c, nil
  }
  
  func foo() (*a, error) {
          return new(a), nil
  }
  
  type a struct{}
  
  func (a *a) bar() (*b, error) {
          return new(b), nil
  }
  
  type b struct{}
  
  func (b *b) baz() (*int, error) {
          return nil, io.EOF // some arbitrary error for demo
  }
This prints a useful stack trace like below and you can know where the error occurred.

  $ go run main.go
  err=EOF
  main.run
          /home/hnakamur/go/src/bitbucket.org/hnakamur/stacktrace-demo/main.go:31
  main.main
          /home/hnakamur/go/src/bitbucket.org/hnakamur/stacktrace-demo/main.go:12
  runtime.main
          /usr/local/go/src/runtime/proc.go:183
  runtime.goexit
          /usr/local/go/src/runtime/asm_amd64.s:2086
  exit status 1