Skip to content

Instantly share code, notes, and snippets.

@drgarcia1986
Last active December 22, 2017 20:10
Show Gist options
  • Save drgarcia1986/07c45c519e2ca4b92206404d68d562a0 to your computer and use it in GitHub Desktop.
Save drgarcia1986/07c45c519e2ca4b92206404d68d562a0 to your computer and use it in GitHub Desktop.
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