Errors Flashcards
What is the last return value in a Go function that returns an error?
The last return value is of type error.
What does a nil error value indicate in Go?
It indicates that the function worked as expected.
How do you check for errors in Go?
Compare the error value to nil.
What is the Go built-in interface for errors?
The error interface with the method Error() string
.
What does errors.New
do in Go?
It creates an error with a string message.
What is the purpose of fmt.Errorf
in Go?
It creates an error with formatted runtime info, using fmt.Printf
verbs.
What is a sentinel error in Go?
A predefined error used to signal specific processing issues, usually declared at the package level.
How do you check for a sentinel error in Go?
Use ==
to compare the returned error with a sentinel error.
Can you define custom error types in Go?
Yes, custom error types can be defined, implementing the Error()
method.
How do you preserve errors with additional information in Go?
Use fmt.Errorf
with the %w
verb to wrap errors.
How can you access the wrapped error in Go?
Use the errors.Unwrap()
function to unwrap and access the original error.
What is required for custom errors to support unwrapping?
Custom errors must implement the Unwrap()
method.
How do you combine multiple errors into one in Go?
Use errors.Join()
to merge multiple errors into a single error.
What does errors.Is
do in Go?
It checks if a specific error is present, including in wrapped errors.
What is the difference between errors.Is
and errors.As
in Go?
errors.Is
checks for specific error instances, while errors.As
checks for a specific error type.
What happens when a panic occurs in Go?
The program exits, and a stack trace is printed.
How do you handle a panic in Go?
Use recover()
in a defer
block to handle the panic and continue execution.
What is the recommended approach for handling errors instead of using panic
and recover
?
Use error wrapping to include stack traces, instead of relying on panic
and recover
.