Last active
December 22, 2017 20:10
-
-
Save drgarcia1986/07c45c519e2ca4b92206404d68d562a0 to your computer and use it in GitHub Desktop.
Golang Error Handling examples
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
// By Type | |
// Go playground https://play.golang.org/p/lJOCJAq8WL | |
package main | |
import "fmt" | |
type ErrorX struct{} | |
func (e *ErrorX) Error() string { | |
return "It's error X" | |
} | |
type ErrorY struct{} | |
func (e *ErrorY) Error() string { | |
return "It's error Y" | |
} | |
func GetErrorX() error { | |
return &ErrorX{} | |
} | |
func main() { | |
err := GetErrorX() | |
switch err.(type) { | |
case *ErrorX: | |
fmt.Println("It's error X") | |
case *ErrorY: | |
fmt.Println("It's error Y") | |
default: | |
fmt.Printf("Error, %s", err) | |
} | |
} |
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
// By Var | |
// Go playground https://play.golang.org/p/JO6EjQBW07 | |
package main | |
import ( | |
"errors" | |
"fmt" | |
) | |
var ( | |
ErrorX = errors.New("error X") | |
ErrorY = errors.New("error Y") | |
) | |
func GetErrorX() error { | |
return ErrorX | |
} | |
func main() { | |
err := GetErrorX() | |
// With switch | |
switch err { | |
case ErrorX: | |
fmt.Println("It's error X") | |
case ErrorY: | |
fmt.Println("It's error Y") | |
default: | |
fmt.Printf("Error, %s", err) | |
} | |
// With if | |
if err == ErrorX { | |
fmt.Println("It's error X") | |
} else if err == ErrorY { | |
fmt.Println("It's error Y") | |
} else { | |
fmt.Printf("Error, %s", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment