Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 RateLimitError that contains two fields: RetryAfter (an int representing seconds) and Endpoint (a string).
  • Implement the Error() string method so it returns a message like: "rate limit exceeded for /users; retry after 30 seconds".
  • Write a function CheckRateLimit(user string) error that simulates a failure by returning a RateLimitError.
  • In your main function, call CheckRateLimit. Use errors.As to detect if the error is a RateLimitError. If it is, print a specific message that only uses the RetryAfter field to tell the user when to come back.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.