Last active
August 6, 2021 11:37
-
-
Save percybolmer/d01bea9fc5e32882c615ffc83343d1b1 to your computer and use it in GitHub Desktop.
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" | |
| "time" | |
| "errors" | |
| ) | |
| // DateError is a custom error that will fulfill the Error interface | |
| type DateError struct { | |
| Message string | |
| Date time.Time | |
| } | |
| // Our Method receiver where we Apply the Error() string function that the error interface needs to the DateError type | |
| func (de DateError) Error() string { | |
| return fmt.Sprintf("%s: %s", de.Date.String(), de.Message) | |
| } | |
| func NewError(message string) DateError { | |
| return DateError{ | |
| Message:message, | |
| Date: time.Now(), | |
| } | |
| } | |
| // PrintError can take in an DateError since DateError fulfills the error interface | |
| func PrintError(err error) { | |
| fmt.Println(err.Error()) | |
| } | |
| func main() { | |
| de := NewError("Auch, I failed") | |
| regularErr := errors.New("Another error") | |
| PrintError(de) | |
| PrintError(regularErr) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment