Created
June 12, 2019 06:53
-
-
Save nobeans/ee3d1711160096472e79abd270333cc4 to your computer and use it in GitHub Desktop.
defferでのエラーのハンドリング
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() { | |
fmt.Println("-----") | |
if err := hoge(); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println("-----") | |
if err := foo(); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println("-----") | |
if err := bar(); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println("-----") | |
if err := baz(); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println("-----") | |
if err := bazz(); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println("-----") | |
if err := bazzz(); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println("-----") | |
if err := bazzzz(); err != nil { | |
fmt.Println(err) | |
} | |
fmt.Println("-----") | |
} | |
func hoge() error { | |
return fmt.Errorf("hoge error!") | |
} | |
func foo() error { | |
defer hoge() | |
return fmt.Errorf("foo error!") | |
} | |
func bar() error { | |
defer func() { | |
if err := hoge(); err != nil { | |
fmt.Println(err) | |
} | |
}() | |
return fmt.Errorf("bar error!") | |
} | |
func baz() (err error) { | |
defer handleDeffer(hoge, &err) | |
return fmt.Errorf("baz error!") | |
} | |
func bazz() (err error) { | |
defer handleDeffer(hoge, &err) | |
return nil | |
} | |
func bazzz() (err error) { | |
defer func() { | |
// errに代入すると、bazzzのerrとして返せる。 | |
if err = hoge(); err != nil { | |
return | |
} | |
}() | |
return nil | |
} | |
func bazzzz() (err error) { | |
defer func() { | |
// errを新規定義(隠蔽)すると、bazzzのerrとして返らない。 | |
if err := hoge(); err != nil { | |
return | |
} | |
}() | |
return nil | |
} | |
func handleDeffer(f func() error, err *error) { | |
err2 := f() | |
if err2 != nil { | |
if *err == nil { | |
*err = err2 | |
} else { | |
fmt.Println("in defer:", err2) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment