Created
October 11, 2023 07:52
-
-
Save akm/2583c1ae0f3a207852bb5af45512c277 to your computer and use it in GitHub Desktop.
Error recovery in deferred function
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
// Use go playground or https://github.com/traefik/yaegi to try | |
func foo(v int) (rerr error) { | |
if v%3 == 1 { | |
defer func() { | |
rerr = fmt.Errorf("error %d mod 3 => 1: overwrite", v) | |
}() | |
} else if v%3 == 2 { | |
defer func() { | |
err := fmt.Errorf("error %d mod 3 => 2: set error if nil", v) | |
if rerr == nil { | |
rerr = err | |
} | |
}() | |
} | |
if v%2 == 0 { | |
return nil | |
} else { | |
return fmt.Errorf("error %d mod 2 => 1: main error", v) | |
} | |
} | |
// > foo(0) | |
// : <nil> | |
// > foo(1) | |
// : error 1 mod 3 => 1: overwrite | |
// > foo(2) | |
// : error 2 mod 3 => 2: set error if nil | |
// > foo(3) | |
// : error 3 mod 2 => 1: main error | |
// > foo(4) | |
// : error 4 mod 3 => 1: overwrite | |
// > foo(5) | |
// : error 5 mod 2 => 1: main error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment