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 count number of repeating words in a given String?
Various examples of printing and formatting in Golang
How to create a photo gallery in Go?
Regular expression for matching HH:MM time format in Golang
Get Hours, Days, Minutes and Seconds difference between two dates [Future and Past]
Encoding and Decoding using json.Marshal and json.Unmarshal
Dynamic JSON parser without Struct in Golang
Regular expression to extract domain from URL
How to blur an image in Golang?
How to Convert string to float type in Go?