To debug and handle errors returned by functions in Go, you can follow these steps:
nil
using the if
statement.result, err := SomeFunction()
if err != nil {
// handle error
}
fmt.Printf
or log.Printf
functions to display the error message along with additional information.result, err := SomeFunction()
if err != nil {
fmt.Printf("Error: %v\n", err)
// handle error
}
result, err := SomeFunction()
if err != nil {
// handle the error, e.g., return an error to the caller
return err
}
type MyError struct {
message string
}
func (e *MyError) Error() string {
return e.message
}
func SomeFunction() error {
// code that can produce an error
if someCondition {
return &MyError{"Some error occurred"}
}
return nil
}
func main() {
result, err := SomeFunction()
if err != nil {
if myErr, ok := err.(*MyError); ok {
// handle specific error type
} else {
// handle general error
}
}
}
recover
function inside a deferred function call. This allows the program to safely continue its execution even if a panic occurs.func SomeFunction() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Panic occurred: %v\n", r)
}
}()
// code that can cause a panic
panic("Something went wrong")
}
By following these steps, you can effectively debug and handle errors returned by functions in Go.