Skip to content

Instantly share code, notes, and snippets.

@styxyang
Created October 8, 2015 08:08
Show Gist options
  • Save styxyang/bc645ecd08e5f6cbb916 to your computer and use it in GitHub Desktop.
Save styxyang/bc645ecd08e5f6cbb916 to your computer and use it in GitHub Desktop.
Detect uncatched errors in Go by @bradfitz http://play.golang.org/p/dqLnEbQFgn
package main
import (
"errors"
"log"
"runtime"
"sync/atomic"
"time"
)
// NeedyError is an error which if unchecked will log an error at the
// next GC. It must be created with NewNeedyError.
type NeedyError struct {
Err error // the underlying error
t time.Time
seen int32
}
func (e *NeedyError) Error() string {
atomic.StoreInt32(&e.seen, 1)
return e.Err.Error()
}
func NewNeedyError(err error) error {
if err == nil {
return nil
}
e := &NeedyError{
Err: err,
t: time.Now(),
}
runtime.SetFinalizer(e, func(ne *NeedyError) {
log.Printf("Unchecked error %v ago: %v", time.Now().Sub(ne.t), ne.Err)
})
return e
}
func doSomething() error {
return NewNeedyError(errors.New("Some error"))
}
func main() {
const check = false
if check {
err := doSomething()
if err != nil {
log.Printf("Got error: %v", err)
}
} else {
// ignoring the error!
doSomething()
}
go func() {
time.Sleep(500 * time.Millisecond)
runtime.GC()
}()
time.Sleep(5 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment