One idea
In Go, useful functions return an error as the last value. nil means success. Any other error means the caller must decide what to do next.
Do not make the caller read a string to understand a known case. Use error values or custom error types for cases your service can handle.
Why this matters
Your HTTP service will fail in normal ways. A product ID may be missing. A map lookup may fail. A request body may be invalid.
Good errors make these failures easy to turn into proper HTTP responses later. Bad errors become random 500s and confusing logs during demos.
Shape errors well
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Repository error
This example uses a map from your data lesson. The repository returns a typed value and a useful error.
The caller can check ErrProductNotFound without comparing text like "not found".
package store
import (
"errors"
"fmt"
)
type Product struct {
ID string
Name string
Price int
}
var ErrProductNotFound = errors.New("product not found")
type ProductStore struct {
items map[string]Product
}
func NewProductStore() ProductStore {
return ProductStore{
items: map[string]Product{
"chai": {ID: "chai", Name: "Masala Chai", Price: 20},
},
}
}
func (s ProductStore) Get(id string) (Product, error) {
p, ok := s.items[id]
if !ok {
return Product{}, fmt.Errorf("get product %q: %w", id, ErrProductNotFound)
}
return p, nil
}Wrap, then check
Use fmt.Errorf with %w when you want to keep the original error inside a clearer message. This gives logs context and still lets code detect the real error.
Later, your HTTP handler can use errors.Is(err, ErrProductNotFound) and return 404 instead of 500.
if errors.Is(err, store.ErrProductNotFound) {
// return HTTP 404 later
}Avoid string checks
Do not write code that checks err.Error() == "product not found". That breaks when you improve the message.
Also avoid panic for expected user mistakes. Missing input, unknown IDs, and invalid values should return errors, not crash your service.
Validate input
Validation is also a good place for useful errors. Keep the message short, but mention the field that failed.
For prices in rupees, reject zero or negative values before saving.
package store
import "fmt"
func ValidateProduct(p Product) error {
if p.ID == "" {
return fmt.Errorf("id is required")
}
if p.Price <= 0 {
return fmt.Errorf("price must be positive: got %d", p.Price)
}
return nil
}Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done