Error Handling Best Practices
Start with Error Handling Best Practices
Good Go error handling is explicit, contextual and useful to the caller, without turning every failure into a panic or a generic message.
What you’ll learn
- Explain the main purpose of error handling best practices.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Check errors near the call, return early on failure, and add operation context when propagating with fmt.Errorf("operation: %w", err). Use errors.Is and errors.As when callers need to react to causes or structured types.
Avoid logging an error and returning it at every layer unless each action serves a clear purpose; repeated handling creates noisy reports. Avoid exposing secrets in error messages. Keep the user-facing message appropriate while preserving useful diagnostic context for developers.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"errors"
"fmt"
"strconv"
)
var ErrInvalidID = errors.New("invalid ID")
func parseID(input string) (int, error) {
id, err := strconv.Atoi(input)
if err != nil {
return 0, fmt.Errorf("parse ID: %w", ErrInvalidID)
}
if id <= 0 {
return 0, fmt.Errorf("validate ID: %w", ErrInvalidID)
}
return id, nil
}
func main() {
for _, raw := range []string{"12", "0", "abc"} {
id, err := parseID(raw)
if err != nil {
fmt.Println("Input:", raw, "invalid:", errors.Is(err, ErrInvalidID))
continue
}
fmt.Println("Valid ID:", id)
}
}
Output
Valid ID: 12
Input: 0 invalid: true
Input: abc invalid: trueTrace what the program does
The valid ID 12 succeeds. The value 0 fails validation and abc fails parsing; both errors wrap the same stable ErrInvalidID sentinel, which errors.Is recognizes in the caller.
Avoid common mistakes
- Check an error before using the result of an operation that can fail.
- Avoid returning sensitive raw input or credentials in error messages and logs.
Try it yourself
Add another accepted ID and a negative ID. Identify the failure stage for each rejected input.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Error Handling Best Practices in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.