Last active
September 11, 2019 08:58
-
-
Save sermojohn/a040f55f436946f15e7dece5d712d8c7 to your computer and use it in GitHub Desktop.
Use of custom error types and switch on error types
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 ( | |
"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