Skip to content

Instantly share code, notes, and snippets.

@sermojohn
Last active September 11, 2019 08:58
Show Gist options
  • Save sermojohn/a040f55f436946f15e7dece5d712d8c7 to your computer and use it in GitHub Desktop.
Save sermojohn/a040f55f436946f15e7dece5d712d8c7 to your computer and use it in GitHub Desktop.
Use of custom error types and switch on error types
package main
import (
"fmt"
)
type ErrorType1 struct {
Message string
}
func (e *ErrorType1) Error() string {
return "type1 - " + e.Message
}
type ErrorType2 struct {
Message string
}
func (e *ErrorType2) Error() string {
return "type2 - " + e.Message
}
func main() {
var error1 error
error1 = &ErrorType1{"test"}
switch es := error1.(type) {
case *ErrorType1:
fmt.Printf("should be type1: %v\n", es)
case *ErrorType2:
fmt.Printf("should be type2: %v\n", es)
}
var error2 error
error2 = &ErrorType2{"test"}
switch es := error2.(type) {
case *ErrorType1:
fmt.Printf("should be type1: %v\n", es)
case *ErrorType2:
fmt.Printf("should be type2: %v\n", es)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment