Error classification in Go

You can preserve the cause of a lookup failure while returning invalid selections as quote data, allowing the pricing endpoint to map each outcome correctly.

Learning outcomes

  • Preserve the original cause of an operation failure while adding context with fmt.Errorf and %w.
  • Recognise missing items through sentinel errors and errors.Is, even after wrapping.
  • Extract structured operation failures with typed errors and errors.As.
  • Return menu selection problems as quote data, separate from Go errors.
  • Map request failures and operation errors to HTTP responses at the handler boundary.
Prerequisite conceptsHTTP status codes

Your POST /v1/menu/price handler receives a request for the Farmhouse pizza, item 1. If the item does not exist, the API must return HTTP 404 with item_not_found. If the item exists but the requested size or options are invalid, the API must return HTTP 200 with every selection error in the quote and both price fields set to 0.

These outcomes describe different kinds of failure. A database lookup can fail as an operation. A selection can be evaluated successfully and still contain problems. Your Go code needs to preserve that distinction until the handler builds the HTTP response.

Go represents ordinary failures with values that implement the error interface. A function usually returns its result alongside an error:

go
type error interface {
    Error() string
}

item, err := loadItem(ctx, itemID)
if err != nil {
    return err
}

A successful operation returns nil for its error. A failed operation returns a value describing the failure. The caller decides whether to return it, inspect it or translate it into another result.

Check errors at the point where you receive them. Ignoring a database error can leave your service working with incomplete data or reporting success when the operation failed. Your lint rules also check that returned errors are handled rather than discarded.

Error wrapping

A service often needs to add context to an error before returning it. Suppose the database query that loads a menu item fails. Returning the database error directly is valid, but the caller does not know which application operation failed.

You can add context with fmt.Errorf:

go
return fmt.Errorf("load item %d: %v", itemID, err)

The %v verb inserts the error's text. It does not preserve the original error as a value that callers can inspect.

Use %w when the caller must be able to identify the underlying cause:

go
return fmt.Errorf("load item %d: %w", itemID, err)

The returned error now carries both the application context and the original cause. This is error wrapping.

For example, a MySQL query may return sql.ErrNoRows. Wrapping it with %w produces an error message like:

load item 1: sql: no rows in result set

The message is useful to a developer, but the preserved cause is more important. A caller can still identify sql.ErrNoRows without comparing the complete message.

FormatBehaviour
%vIncludes the original error's text, but does not wrap it
%wIncludes the text and preserves the original error in the wrapping chain

Use %w when callers should be able to inspect or handle the underlying cause. Use %v when you deliberately want to include an error's text without exposing its identity through the wrapping chain.

Wrapping is also an API design decision. When your package wraps a database-specific error, callers can inspect that database error. Only expose that relationship when callers have a reason to depend on it.

Unwrapping errors

A wrapped error retains a relationship with its original cause. The errors package provides errors.Unwrap to retrieve the immediate underlying error from a conventional wrapper.

go
original := sql.ErrNoRows
wrapped := fmt.Errorf("load item: %w", original)

underlying := errors.Unwrap(wrapped)
// underlying is sql.ErrNoRows

You could call errors.Unwrap repeatedly to walk a simple chain. Most application code should use errors.Is or errors.As instead. They inspect the wrapping chain without requiring callers to know how many layers added context.

Sentinel errors

Sometimes a caller needs to recognise a condition, but does not need additional fields describing it. A missing item is one example.

Define a package-level error for that condition:

go
var ErrItemNotFound = errors.New("item not found")

This is a sentinel error. It gives your application a stable value representing a particular failure condition.

The service can translate the database's no-row result into this application-level condition:

go
if errors.Is(err, sql.ErrNoRows) {
    return Item{}, fmt.Errorf("item %d: %w", itemID, ErrItemNotFound)
}
if err != nil {
    return Item{}, fmt.Errorf("load item %d: %w", itemID, err)
}

The service distinguishes a missing item from an unexpected database failure. It does not need to know anything about HTTP.

The handler can recognise the sentinel after the service has added context:

go
if errors.Is(err, ErrItemNotFound) {
    // Return HTTP 404 with item_not_found.
    return
}

errors.Is traverses the wrapping chain and checks whether an error matches the target. The handler does not need to know how many times another layer wrapped the sentinel.

Error identity

Direct equality works only when the error value is exactly the value being compared:

go
if err == ErrItemNotFound {
    // Handle missing item.
}

Once a caller wraps the sentinel with %w, the outer error is a different value. The original sentinel remains in its wrapping chain, but err == ErrItemNotFound is false.

Define sentinels for conditions callers need to recognise. Avoid creating a separate sentinel for every possible error message. A sentinel should represent a meaningful condition, such as a missing item, rather than duplicate information already present in an error string.

Typed errors

A sentinel is enough when the caller only needs to identify a condition. Sometimes the caller needs structured information about an operation failure.

Consider an order state transition in a later part of the course. A transition error may need to report both the current state and the requested state. A plain sentinel cannot carry those values.

A custom error type can:

go
type IllegalTransitionError struct {
    From string
    To   string
}

func (e *IllegalTransitionError) Error() string {
    return fmt.Sprintf(
        "cannot move order from %s to %s",
        e.From,
        e.To,
    )
}

Because *IllegalTransitionError implements Error() string, it satisfies the error interface. The caller can inspect its fields instead of parsing the message.

Use errors.As to find a typed error in a wrapping chain:

go
var transitionErr *IllegalTransitionError

if errors.As(err, &transitionErr) {
    fmt.Println(transitionErr.From)
    fmt.Println(transitionErr.To)
}

The target passed to errors.As is a pointer to the variable where the matching error should be stored. Here, transitionErr is already a pointer to IllegalTransitionError, so &transitionErr has type **IllegalTransitionError.

Passing transitionErr directly is incorrect:

go
var transitionErr *IllegalTransitionError

errors.As(err, transitionErr)

The target is not a valid pointer to a destination variable. errors.As panics when its target is invalid.

Choosing an error representation

Use the representation that matches what the caller needs to do with the failure.

SituationRepresentation
A menu item does not existSentinel such as ErrItemNotFound
An order transition is not allowed and the caller needs both statesTyped error such as *IllegalTransitionError
A database operation fails unexpectedlyWrap the underlying error with context
A menu selection contains invalid optionsSelection errors in the quote, not Go errors

A typed error is useful when callers need structured fields from an operation failure. It is not a reason to turn every validation problem into a Go error. The menu configurator has a different contract, which determines how its selection problems must be represented.

Multiple operation failures

Sometimes independent operations fail during the same task. Go provides errors.Join to combine those failures into one error value.

go
joined := errors.Join(errA, errB)

if errors.Is(joined, errA) {
    fmt.Println("first operation failed")
}

The joined error retains its component errors. Callers can still use errors.Is and errors.As to inspect them. errors.Join ignores nil values and returns nil when every supplied error is nil.

Use it when a function needs to return multiple independent operation failures through an error value. It is not a replacement for a structured validation result. The menu configurator needs to return every selection problem in a predictable JSON field, with the relevant identifiers attached to each problem.

Validation results and operation errors

The menu configurator evaluates a requested item, size, option groups and selected options. A request can contain several selection problems at once. For example, a group can have too few selected options while another selection contains an unavailable option.

Returning only the first problem forces the customer to submit the request repeatedly. Each response reveals another problem that could have been reported in the first evaluation.

The configurator should collect every applicable selection error. Its quote contains an errors array of structured selection-error records:

go
type Quote struct {
    Description string           `json:"description"`
    UnitPaise   int64            `json:"unit_paise"`
    TotalPaise  int64            `json:"total_paise"`
    Errors      []SelectionError `json:"errors"`
}

Each selection error has a code and a non-empty message. It can also carry identifiers that tell the client which selection caused the problem.

The API defines six selection error codes:

CodeMeaning
size_not_offeredThe item has no price for the requested size
unknown_groupA selected group does not belong to the item
selection_countA group's selection count is below min_select or above max_select
duplicate_optionThe same option was selected more than once in a group
unknown_optionThe option ID does not belong to that group
option_unavailableThe option is out of stock, or has neither an exact-size price nor a * price

The identifiers depend on the error. size_not_offered has no group_id or option_id. unknown_group and selection_count include group_id. duplicate_option, unknown_option and option_unavailable include both group_id and option_id.

A group omitted from chosen counts as having zero selections. Selecting an option in the wrong group produces unknown_option. Report duplicate options and collect multiple independent problems in the same evaluation.

The size check also affects which other problems apply. When the item does not offer the requested size, return size_not_offered without also reporting option availability errors. An out-of-stock option is unavailable even when a price record exists for it.

These records are data, not values implementing Go's error interface. The errors JSON field does not represent a Go error chain. It describes problems with the submitted selection.

When the item exists but the selection is invalid, the endpoint returns HTTP 200. Both unit_paise and total_paise must be 0, and the quote must contain every applicable selection error. The configurator has successfully evaluated the selection and produced the result required by the API.

Promotion timing

A promotion must not make an invalid selection payable. The configurator first needs to establish that the complete selection is valid.

Only a valid selection can proceed to price calculation and promotion rules. If the quote contains selection errors, leave both price fields at zero and do not apply promotions. This keeps validation separate from the calculation of a payable price.

HTTP error mapping

An error value describes an application or infrastructure failure. An HTTP response communicates the result to the API client. The handler is the boundary that understands both.

Your service should return domain errors and wrapped database errors. It should not decide whether an error becomes HTTP 400, 404 or another status. Keep that mapping in the HTTP layer, using the project's HTTP status codes.

For POST /v1/menu/price, the contract distinguishes request failures, missing items and invalid selections:

ConditionHTTP statusError code or response
Malformed JSON or a body that is not one valid object of the expected shape400invalid_body
An out-of-range field400invalid_parameter, with field
Body larger than 64 KiB413body_too_large
Item does not exist404item_not_found
Item exists but its selection is invalid200Quote with all selection errors and both prices set to 0

Malformed request bodies include arrays, unknown fields, incorrect field types, multiple JSON objects and truncated JSON. They are not selection errors.

An out-of-range item_id, an empty or missing size, a qty outside 1 through 20, or a chosen key that is not a positive integer produces invalid_parameter. The response includes the relevant field name. These checks concern the request itself, before the configurator evaluates a selection.

A missing item is an operation outcome. The service returns an error that the handler can identify with errors.Is. The handler maps it to HTTP 404 and the stable code item_not_found.

An invalid selection is different. The configurator returns a quote with its selection errors. The handler returns that quote with HTTP 200. It must not convert those selection errors into HTTP 400 or HTTP 500.

This boundary keeps the service independent of HTTP and prevents a validation result from being confused with an operation failure.

A database no-row error is wrapped by the service and mapped by the handler to HTTP 404, while multiple configurator validation problems are collected into Quote.Errors and returned as HTTP 200.A database no-row error is wrapped by the service and mapped by the handler to HTTP 404, while multiple configurator validation problems are collected into Quote.Errors and returned as HTTP 200.

Logging and public errors

Wrapping an error with useful context helps developers find the operation that failed. The service can add an item ID or operation name without deciding what message a client should see.

For example, the handler or service can log the returned error:

go
slog.Error(
    "item lookup failed",
    "item_id", itemID,
    "err", err,
    "request_id", requestID,
)

The wrapped error chain provides diagnostic detail. The request ID lets you connect the log entry to the request handled by your middleware.

Keep the public response contract stable even when the database driver or internal service structure changes. A client should rely on an error code and the documented response fields, not on the text of a database error.

Panics and expected failures

Go also provides panic. It interrupts normal execution and begins unwinding the current goroutine's call stack. It is not the ordinary way to report a failed operation.

A missing item, an unavailable size, an unknown option or an invalid quantity is an expected condition. Handle it explicitly through an error or a structured validation result. These conditions should not panic.

A malformed request must not crash the API through an ordinary validation path. Likewise, recover is not a replacement for checking errors. Recovery belongs at carefully chosen process boundaries, where it can prevent an unexpected programming failure from terminating a whole server process.

Error boundaries in menu pricing

The exercise POST /v1/menu/price: price a configured item brings these distinctions together. The handler must recognise malformed bodies and invalid request fields. The service must distinguish a missing item from an unexpected database failure. The configurator must report every selection problem as quote data.

Keep the boundary clear: a missing item is an operation error that maps to item_not_found; an invalid selection is a successful evaluation with an errors array. A quote with selection errors has zero prices, and promotions apply only after a valid selection.

Check your understanding

Question 1 of 4

The service loads item 1 and receives sql.ErrNoRows. It wraps the missing-item sentinel with fmt.Errorf("load item: %w", ErrItemNotFound). Which handler check still identifies the missing item?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (Go 1.25 errors and fmt).

Finished Lesson 2.13?