Creating Custom Errors
Start with Creating Custom Errors
A custom error type can carry structured details that callers need beyond a human-readable message.
What you’ll learn
- Explain the main purpose of creating custom errors.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Define a struct with relevant fields, then implement Error() string. Its values satisfy error and can also be inspected by type assertion or errors.As.
Store stable, meaningful fields such as an invalid input value or operation name, rather than forcing callers to parse an error message string. If you use a pointer-receiver Error method, return an actual non-nil pointer on failure.
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 "fmt"
type RangeError struct{ Value int }
func (e RangeError) Error() string {
return fmt.Sprintf("%d is outside 1..10", e.Value)
}
func check(n int) error {
if n < 1 || n > 10 {
return RangeError{Value: n}
}
return nil
}
func main() {
err := check(15)
fmt.Println("Error:", err)
if issue, ok := err.(RangeError); ok {
fmt.Println("Invalid value:", issue.Value)
}
}
Output
Error: 15 is outside 1..10
Invalid value: 15Trace what the program does
check returns a RangeError carrying the rejected value 15. The caller prints its message, then asserts the concrete error type and reads Value as structured data.
Avoid common mistakes
- Do not require callers to scrape the printed message to find a structured field.
- Choose value or pointer receiver consistently with the concrete type you return and inspect.
Try it yourself
Extend RangeError with a Name field and display it both in Error() and the caller’s structured handling.
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 Creating Custom Errors 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.