Error() methodcheckAge that returns an error if age is less than 18checkAge with a specific age and handle the errorError() methodcheckAge that returns an error if age is less than 18checkAge with a specific age and handle the errorAgeError with a field message of type string.Use type AgeError struct { message string } to define the struct.
Error() to AgeError that returns the message field as a string.The method signature should be func (e AgeError) Error() string and return e.message.
checkAge that takes an age of type int and returns an error. If age is less than 18, return an AgeError with the message "Age is less than 18". Otherwise, return nil.Use an if statement to check the age and return the custom error or nil.
main function, call checkAge with the value 16. If an error is returned, print the error message using fmt.Println(err).Use err := checkAge(16) and then check if err != nil to print the error.
What does the Error() method in Go's error interface return?
error interface in Go defines a single method Error() that returns a string.Error() method returns a string that describes the error message.Which of the following is the correct way to declare a function in Go that returns an error?
func doSomething() ???
error type as the last return value.func doSomething() error.What will be the output of the following Go program?
package main
import (
"errors"
"fmt"
)
func main() {
err := errors.New("file not found")
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("No error")
}
}errors.New function creates a new error with the message "file not found".err is not nil, the program prints err.Error(), which is the string "file not found".Identify the error in this Go code snippet:
func check() error {
var err error
if err != nil {
return err
}
return nil
}err is declared but never assigned a value, so it defaults to nil.err is nil, the condition err != nil is false, so the return inside if never runs.Given this Go function that returns an error, how can you modify it to wrap the original error with additional context?
func readFile() error {
return errors.New("file missing")
}Choose the best way to add context "readFile failed:" before the original error message.
fmt.Errorf with the %w verb to wrap an error with context.fmt.Errorf("readFile failed: %w", errors.New("file missing")), which correctly wraps the original error with context.errors.Wrap which is not in standard Go. return fmt.Errorf("readFile failed: %v", errors.New("file missing")) uses %v which formats but does not wrap the error.Pass the test and this pattern moves unknown