Created
September 10, 2024 15:14
-
-
Save kyrylo/6a62bfbd69b23f79df0757c1941af6dc to your computer and use it in GitHub Desktop.
How to wrap errors in Go (wrong)
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
// Correct way | |
package main | |
import ( | |
"errors" | |
"fmt" | |
) | |
var errDoopsy = errors.New("doopsy") | |
func main() { | |
err := fmt.Errorf("oopsy: %w", newError("doopsy")) | |
if errors.Is(err, errDoopsy) { | |
fmt.Println("doopsy error") | |
} else { | |
fmt.Println("unknown error") | |
} | |
} | |
func newError(s string) error { | |
switch s { | |
case errDoopsy.Error(): | |
return errDoopsy | |
default: | |
return errors.New(s) | |
} | |
} |
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
// Wrong way | |
package main | |
import ( | |
"errors" | |
"fmt" | |
) | |
var errDoopsy = errors.New("doopsy") | |
func main() { | |
err := fmt.Errorf("oopsy: %v", newError("doopsy")) | |
if errors.Is(err, errDoopsy) { | |
fmt.Println("doopsy error") | |
} else { | |
fmt.Println("unknown error") | |
} | |
} | |
func newError(s string) error { | |
switch s { | |
case errDoopsy.Error(): | |
return errDoopsy | |
default: | |
return errors.New(s) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment