Last active
August 29, 2015 13:57
-
-
Save glyn/9527053 to your computer and use it in GitHub Desktop.
Goroutine panic wrapper. The objective is to be able to launch goroutines and tell if any of them have panicked. The primary use for this is in a testing framework where we want testcases to abort when an assertion fails and we sometimes want to use goroutines in tests.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func main() { | |
defer func() { | |
if e := recover(); e != nil { | |
fmt.Printf("Recovered from '%v'\n", e) | |
} | |
}() | |
panicChannel := Go(func() { | |
panic("child failed") | |
}) | |
check(panicChannel) | |
} | |
type PanicChannel <-chan interface {} | |
/* | |
Check the given channels and panic if any of them returns a value. | |
*/ | |
func check(panicChannels ...PanicChannel) { | |
for _, panicChannel := range panicChannels { | |
if err, ok := <- panicChannel; ok { | |
panic(err) | |
} | |
} | |
} | |
/* | |
Run the given function in a goroutine and report any panic on the returned | |
channel. If the goroutine returns without panicking, close the returned channel. | |
*/ | |
func Go(f func()) PanicChannel { | |
panicChannel := make(chan interface {}) | |
go func(){ | |
defer func() { | |
if err := recover(); err != nil { | |
panicChannel <- err | |
} else { | |
close(panicChannel) | |
} | |
}() | |
f() | |
}() | |
return panicChannel | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment