liveBook · Manning

Status.Error

As explained in Learn Go with Pocket-Sized Projects

status.Error and its formatting variant construct errors carrying gRPC status codes and messages.

Use status.Error or status.Errorf at a gRPC endpoint boundary so failures carry a gRPC status code and message. Endpoint returns should otherwise return nil errors. section 10.3.2

Translate known domain failures such as InvalidInputError into codes.InvalidArgument; format unexpected failures with codes.Internal and useful context. section 10.3.2

Mapping a habit-creation failure

got, err := habit.Create(ctx, h) if err != nil { var invalidErr habit.InvalidInputError if errors.As(err, &invalidErr) { return nil, status.Error(codes.InvalidArgument, invalidErr.Error()) } return nil, status.Errorf(codes.Internal, "cannot save habit %v: %s", h, err.Error()) }

Listing 10.18 create.go: Error management
got, err := habit.Create(ctx, h)
if err != nil {
    var invalidErr habit.InvalidInputError
    if errors.As(err, &invalidErr) {
        return nil, status.Error(codes.InvalidArgument, invalidErr.Error())
    }
    // other error
    return nil, status.Errorf(codes.Internal, "cannot save habit %v: %s", 
        h, err.Error())
}

Inspect the complete endpoint error branch, including errors.As, status.Error, status.Errorf, and the selected gRPC codes. section 10.3.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Demonstrates errors.As classification and formatted status construction, without detailing status internals.
Examples
Uses habit creation, InvalidInputError, and formatted database-like failure context.
What it assumes
Assumes Go error handling and gRPC endpoint code; teaches status construction and domain-error mapping.
What you can do after
Apply it via google.golang.org/grpc/status to return classified errors from gRPC endpoints.
How it connects
Connects gRPC status codes with errors.As, codes.InvalidArgument, and codes.Internal.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.