Skip to content

Instantly share code, notes, and snippets.

@vanhtuan0409
Created April 5, 2021 06:57
Show Gist options
  • Save vanhtuan0409/7cda71876c93498f8f058eae0405314e to your computer and use it in GitHub Desktop.
Save vanhtuan0409/7cda71876c93498f8f058eae0405314e to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"testing"
)
// run test
// go test .
//
// run bench
// go test -bench=.
//
// results:
// goos: linux
// goarch: amd64
// pkg: github.com/vanhtuan0409/go-handle-error
// cpu: Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz
// BenchmarkPanic-8 5318145 226.4 ns/op
// BenchmarkNormal-8 1000000000 0.2616 ns/op
// PASS
// ok github.com/vanhtuan0409/go-handle-error 1.726s
func PanicError() (err error) {
defer func() {
r := recover()
err, _ = r.(error)
}()
panic(errors.New("error"))
}
func NormalError() error {
return errors.New("error")
}
func TestCorrectness(t *testing.T) {
var err error
err = PanicError()
if err == nil {
t.Error("Failed PanicError")
return
}
err = NormalError()
if err == nil {
t.Error("Failed NormalError")
return
}
}
func BenchmarkPanic(b *testing.B) {
for i := 0; i < b.N; i++ {
PanicError()
}
}
func BenchmarkNormal(b *testing.B) {
for i := 0; i < b.N; i++ {
NormalError()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment