Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
25: Custom Error Types
A few years ago, I was reviewing a PR for a teammate who was building a complex payment processing pipeline. He had a function that validated incoming transactions, and it returned a standard errors.New("invalid transaction") whenever something went wrong. It seemed fine at first, but when we hit production, our logs were a nightmare. We knew transactions were failing, but we had no idea why. Was it a negative amount? An expired credit card? A currency mismatch? To find out, he was actually parsing the error string—literally doing if strings.Contains(err.Error(), "expired")—which is a fragile, ugly way to handle logic.
That's the moment where you realize that while errors.New is great for simple failures, it's useless when the calling code needs to make a decision based on the type of failure. In Go, an error is just an interface. This is incredibly powerful because it means we can attach as much metadata to an error as we want, as long as we provide a string representation of it.
Defining a Structured Error
To create a custom error, you define a struct to hold the specific data you need and then implement the error interface by adding an Error() string method. Let's look at a better way to handle that transaction validation scenario. Instead of a generic string, we can create a ValidationError type that tells us exactly which field failed and why.
type ValidationError struct {
Field string
Reason string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("field %s: %s", e.Field, e.Reason)
}
func ValidateAmount(amount float64) error {
if amount <= 0 {
return &ValidationError{
Field: "amount",
Reason: "must be greater than zero",
}
}
return nil
}
I used a pointer receiver (*ValidationError) here. In Go, it's a common convention to return pointers to custom error structs. It avoids copying the struct and makes it clearer when you're dealing with a specific error instance.
Extracting Data with errors.As
Creating the custom error is only half the battle. The real magic happens when you catch that error. You don't want to parse strings; you want to access the Field and Reason properties directly. While you could use a type assertion, the modern and idiomatic way to do this is with errors.As.
errors.As is smarter than a simple type cast because it can "unwrap" errors. If your custom error was wrapped inside another error (using fmt.Errorf("... %w", err)), errors.As will dig through the layers until it finds the target type.
err := ValidateAmount(-10.50)
if err != nil {
var valErr *ValidationError
if errors.As(err, &valErr) {
// Now we have access to the specific fields!
fmt.Printf("The user messed up the %s field. Reason: %s\n", valErr.Field, valErr.Reason)
} else {
// This is some other kind of error we didn't expect
fmt.Println("An unexpected error occurred:", err)
}
}
By doing this, your error handling becomes a first-class part of your API. You're no longer guessing based on text; you're using the type system to drive your application's recovery logic.
📋 Practical Task
Implementing a Sophisticated API Rate Limit Handler
Imagine you are building a public API. When a user hits their rate limit, you don't just want to tell them "Too Many Requests"; you want to tell them exactly how many seconds they need to wait before trying again.
Your Task:
- Create a custom error struct called
RateLimitErrorthat contains two fields:RetryAfter(anintrepresenting seconds) andEndpoint(astring). - Implement the
Error() stringmethod so it returns a message like:"rate limit exceeded for /users; retry after 30 seconds". - Write a function
CheckRateLimit(user string) errorthat simulates a failure by returning aRateLimitError. - In your
mainfunction, callCheckRateLimit. Useerrors.Asto detect if the error is aRateLimitError. If it is, print a specific message that only uses theRetryAfterfield to tell the user when to come back.
There are no comments for now.