Last active
June 15, 2022 01:58
-
-
Save jerryan999/d70380fa2b235213f70779b94231b27b to your computer and use it in GitHub Desktop.
different golang error implementation
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" | |
import "fmt" | |
func bar() error { | |
return errors.New("an error") | |
} | |
func main() { | |
err := bar() | |
fmt.Println(err) | |
} |
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" | |
) | |
var ErrDivideByZero = errors.New("divide by zero") | |
func Divide(a, b int) (int, error) { | |
if b == 0 { | |
return 0, ErrDivideByZero | |
} | |
return a / b, nil | |
} | |
func main() { | |
a, b := 5, 0 | |
result, err := Divide(a, b) | |
if err != nil { | |
switch { | |
case errors.Is(err, ErrDivideByZero): | |
fmt.Println("Divide by zero") | |
default: | |
fmt.Printf("unknown error: %v\n", err) | |
} | |
} | |
fmt.Printf("%d / %d = %d\n", a, b, result) | |
} |
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" | |
) | |
var ErrDivideByZero = errors.New("divide by zero") | |
func doDivide(a, b int) (int, error) { | |
result, err := Divide(a, b) | |
if err != nil { | |
return 0, fmt.Errorf("divide error: %w", err) | |
} | |
return result, nil | |
} | |
func Divide(a, b int) (int, error) { | |
if b == 0 { | |
return 0, ErrDivideByZero | |
} | |
return a / b, nil | |
} | |
func main() { | |
a, b := 5, 0 | |
result, err := doDivide(a, b) | |
if err != nil { | |
switch { | |
case errors.Is(err, ErrDivideByZero): | |
fmt.Println("Divide by zero") | |
default: | |
fmt.Printf("unknown error: %v\n", err) | |
} | |
} | |
fmt.Printf("%d / %d = %d\n", a, b, result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment