Skip to content

Instantly share code, notes, and snippets.

@drgarcia1986
Last active Dec 22, 2017
Embed
What would you like to do?
Golang Error Handling examples
// 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)
}
}
// 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