Concept Flow - Error interface
Start
Call function returning error
Check if error is nil
Handle error
End
This flow shows how Go functions return errors and how to check and handle them.
package main import ( "errors" "fmt" ) func doTask() error { return errors.New("something went wrong") } func main() { err := doTask() if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Success") } }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Call doTask() | doTask() returns error | error with message 'something went wrong' |
| 2 | Assign error to err | err = error object | err holds error |
| 3 | Check if err != nil | err is not nil | Condition true |
| 4 | Print error message | fmt.Println("Error:", err) | Output: Error: something went wrong |
| 5 | End program | No further code | Program terminates |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| err | nil | error object created | error object assigned | error object checked (not nil) | error object held |
Error interface in Go: - Functions return error type to signal problems. - Check if error is nil before handling. - Use errors.New() to create errors. - Print error directly calls Error() method. - Always handle errors to avoid silent failures.
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