Example to create custom error
Example
package main
import (
"errors"
"fmt"
"time"
)
type CustomError struct {
message string
function string
timestamp time.Time
}
func (e *CustomError) Error() string {
return e.message
}
func (e *CustomError) GetHost() time.Time {
return e.timestamp
}
func main() {
errs := []interface{}{
CustomError{"Custom error.", "host01.local", time.Now()},
errors.New("Generic error"),
}
for _, e := range errs {
if v, ok := e.(CustomError); ok {
fmt.Println("Error: ", v.Error())
fmt.Println(" -> This error is of type CustomError")
} else {
fmt.Println("Error: ", v.Error())
fmt.Println(" -> This error is generic")
}
}
}
Output
Error: Custom error.
-> This error is of type CustomError
Error:
-> This error is generic
Most Helpful This Week
How to fetch an Integer variable as String in Go?
How to convert Go struct to JSON?
Subtract N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time.
Strip all white spaces, tabs, newlines from a string
How to kill execution of goroutine?
Example to use Weekday and YearDay function