A. The error check in main should be err == nil, not err != nil
B. The defer statement is misplaced and should be before error check
C. The function readFile should return a string, not error
D. os.Open does not return an error
Solution
Step 1: Examine the error handling in main
The main function calls readFile() and prints "File read successfully" if err != nil.
Step 2: Identify the logic error
err != nil means an error occurred, so printing success here is incorrect. Success should be printed only if err == nil (no error).
Final Answer:
The error check in main should be err == nil, not err != nil -> Option A
Quick Check:
Print success only if err == nil [OK]
Hint: Print success only when err == nil, not err != nil [OK]
Common Mistakes:
Confusing err == nil and err != nil conditions
Moving defer before error check incorrectly
Expecting os.Open to never return error
5. You want to write a Go function that tries to open a file and returns a custom error message if it fails. Which code snippet correctly wraps the original error with a custom message using Go's standard library?
hard
A. file, err := os.Open("config.json")
if err != nil {
panic(err)
}
return file.Close()
B. file, err := os.Open("config.json")
if err != nil {
return errors.New("failed to open config")
}
return file.Close()
C. file, err := os.Open("config.json")
if err != nil {
return fmt.Errorf("failed to open config: %w", err)
}
return file.Close()
D. file, err := os.Open("config.json")
if err != nil {
return err.Error()
}
return file.Close()
Solution
Step 1: Understand error wrapping in Go
Go 1.13+ supports wrapping errors with fmt.Errorf and %w verb to keep original error context.
Step 2: Check each option for correct wrapping
file, err := os.Open("config.json")
if err != nil {
return fmt.Errorf("failed to open config: %w", err)
}
return file.Close() uses fmt.Errorf with %w to wrap original error, preserving it. file, err := os.Open("config.json")
if err != nil {
return errors.New("failed to open config")
}
return file.Close() creates new error losing original error. file, err := os.Open("config.json")
if err != nil {
panic(err)
}
return file.Close() panics instead of returning error. file, err := os.Open("config.json")
if err != nil {
return err.Error()
}
return file.Close() returns string instead of error type.
Final Answer:
file, err := os.Open("config.json")
if err != nil {
return fmt.Errorf("failed to open config: %w", err)
}
return file.Close() -> Option C
Quick Check:
Use fmt.Errorf with %w to wrap errors [OK]
Hint: Use fmt.Errorf("%w") to wrap errors with context [OK]
Common Mistakes:
Replacing original error instead of wrapping
Using panic instead of returning error
Returning error message string instead of error type
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.