Last active
August 16, 2019 03:01
-
-
Save jgoc/35509fb4a04b4e280bc8d5383699f94b to your computer and use it in GitHub Desktop.
golang error message stacking
This file contains hidden or 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 ( | |
"errors" | |
"fmt" | |
) | |
func main() { | |
flow() | |
fmt.Println("continued") | |
} | |
// check will stack the error messages | |
// init is the error prefix | |
// err is the error to be concatinated | |
// cont will determine which check calls triggers the panic | |
// result will be used for the next check concatinations | |
func check(init, err error, cont bool) (result error) { | |
if init == nil { | |
init = errors.New("") | |
} | |
result = fmt.Errorf("%s\n%s", init, err) | |
if !cont && err != nil { | |
panic(result) | |
} | |
return | |
} | |
func flow() { | |
defer func() { | |
if err := recover(); err != nil { | |
fmt.Println("err: ", err) | |
} | |
}() | |
err := errors.New("ok") | |
err = check(nil, err, true) | |
err1 := errors.New("ok 2") | |
err = check(err, err1, false) | |
err2 := errors.New("ok 3") | |
err = check(err, err2, true) | |
fmt.Println("Hello, playground") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment