Error
package main
import (
"errors"
"fmt"
)
// Function f1 returns the result of arg + 3, or an error if arg is 42
func f1(arg int) (int, error) {
if arg == 42 {
return -1, errors.New("can't work with 42")
}
return arg + 3, nil
}
// Define a custom error type argError, which includes information about the argument and the problem
type argError struct {
arg int
prob string
}
// Implement the Error method for the argError type
func (e *argError) Error() string {
return fmt.Sprintf("%d - %s", e.arg, e.prob)
}
// Function f2 returns the result of arg + 3, or a custom argError if arg is 42
func f2(arg int) (int, error) {
if arg == 42 {
return -1, &argError{arg, "can't work with it"}
}
return arg + 3, nil
}
func main() {
// Use f1 and handle the error
for _, i := range []int{7, 42} {
if r, e := f1(i); e != nil {
fmt.Println("f1 failed:", e)
} else {
fmt.Println("f1 worked:", r)
}
}
// Use f2 and handle the custom error type
for _, i := range []int{7, 42} {
if r, e := f2(i); e != nil {
fmt.Println("f2 failed:", e)
} else {
fmt.Println("f2 worked:", r)
}
}
// Demonstrate type assertion to access fields of the custom error type
_, e := f2(42)
if ae, ok := e.(*argError); ok {
fmt.Println("Custom error type:")
fmt.Println(ae.arg)
fmt.Println(ae.prob)
}
}Output
Last updated