Senior
How do you handle errors in Go in a production-ready application?
sobes.tech AI
Answer from AI
In Go, error handling is based on explicit checking of the returned error value after function calls. In production-ready applications, it is important to:
- Always check errors immediately after calling a function.
- Use error wrapping (
fmt.Errorfwith%w) to preserve context. - Log errors with sufficient detail, including call stacks if necessary.
- For critical errors, apply retry strategies or fallback.
- In HTTP services, return correct status codes and understandable messages.
Example of error handling with wrapping and logging:
package main
import (
"errors"
"fmt"
"log"
)
func doSomething() error {
return errors.New("original error")
}
func main() {
err := doSomething()
if err != nil {
wrappedErr := fmt.Errorf("error in doSomething: %w", err)
log.Printf("An error occurred: %v", wrappedErr)
// Additional handling, e.g., returning the error upwards
}
}