Go Errors
In Go, errors are represented by values of the built-in error interface type. The error type is defined as follows:
type error interface {
Error() string
}
Any type that has an Error() method that returns a string can be used as an error in Go.
Here's an example of how to define and use custom errors in Go:
type MyError struct {
message string
}
func (e *MyError) Error() string {
return e.message
}
func doSomething() error {
return &MyError{"something went wrong"}
}
func main() {
err := doSomething()
if err != nil {
fmt.Println("Error:", err)
}
}
In this example, we define a custom error type MyError, which has a message field and an Error() method that returns the value of the message field. We then define a function doSomething() that returns an error of type MyError if something goes wrong. Finally, in the main() function, we call doSomething() and check for errors using the != nil syntax. If an error occurs, we print the error message to the console.
In addition to custom errors, Go provides a built-in errors.New() function for creating errors with a custom error message:
func doSomething() error {
return errors.New("something went wrong")
}
This will return an error of type *errors.errorString, which implements the error interface with the given error message as the string representation of the error.
Go also provides a panic() function for handling exceptional situations, which is similar to throwing an exception in other programming languages. When a panic() occurs, the program will stop executing and print a stack trace of the error. It's generally recommended to use errors for normal error handling and panics for exceptional situations.
func doSomething() {
panic("something went horribly wrong")
}
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Println("Panic:", err)
}
}()
doSomething()
}
In this example, we define a function doSomething() that panics with a custom error message. In the main() function, we use a defer statement to recover from the panic and print the error message to the console. The recover() function returns the error message that was passed to the panic() function.
