Junior — Middle
How to handle and provide an informative error message in an application?
sobes.tech AI
Answer from AI
In Go, the error type and the fmt.Errorf function are commonly used to handle errors and provide informative messages.
Example of handling and passing an error with a message:
func readFile(filename string) error {
data, err := os.ReadFile(filename)
if err != nil {
return fmt.Errorf("failed to read file %s: %w", filename, err)
}
// process data
return nil
}
Here:
- Error wrapping is used with
%wto preserve the original error. - The message contains context about what exactly happened and where.
When calling the function, you can check the error and print it:
err := readFile("config.json")
if err != nil {
log.Println("Error reading file:", err)
}
This approach helps quickly understand the source and cause of the error, which is important for debugging and maintaining the application.