Created
October 6, 2017 20:18
-
-
Save hartfordfive/8e883be8d5b3a2d14766d5f77e095684 to your computer and use it in GitHub Desktop.
Custom Go Errors Examples
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 ( | |
"errors" | |
"fmt" | |
"time" | |
) | |
type HostError struct { | |
message string | |
host string | |
timestamp time.Time | |
} | |
func (e *HostError) Error() string { | |
return e.message | |
} | |
func (e *HostError) GetHost() time.Time { | |
return e.timestamp | |
} | |
type ExecutionError struct { | |
message string | |
function string | |
timestamp time.Time | |
} | |
func (e *ExecutionError) Error() string { | |
return e.message | |
} | |
func (e *ExecutionError) GetHost() time.Time { | |
return e.timestamp | |
} | |
func main() { | |
errs := []interface{}{ | |
HostError{"Host error.", "host01.local", time.Now()}, | |
ExecutionError{"Function could not successfully execute.", "build()", time.Now()}, | |
errors.New("Generic error"), | |
} | |
for _, e := range errs { | |
if v, ok := e.(HostError); ok { | |
fmt.Println("Error: ", v.Error()) | |
fmt.Println(" -> This error is of type HostError") | |
} else if v, ok := e.(ExecutionError); ok { | |
fmt.Println("Error: ", v.Error()) | |
fmt.Println(" -> This error is of type ExecutionError") | |
} else { | |
fmt.Println("Error: ", v.Error()) | |
fmt.Println(" -> This error is generic") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment