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
Regular expression to validate email address
How to replace emoji characters in string using regex in Golang?
How to use wildcard or a variable in our URL for complex routing?
Anonymous Functions in Golang
Regular expression to validate the date format in "dd/mm/yyyy"
How to check if a string contains a substring in Golang?