Error Details

Returning rich error details with field violations.

Server — main.go

import (
	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"shortener/pb"
)

func validateCreateLink(req *pb.CreateLinkRequest) error {
	if req.GetUrl() == "" {
		st := status.New(codes.InvalidArgument, "validation failed")
		detailed, _ := st.WithDetails(&errdetails.BadRequest{
			FieldViolations: []*errdetails.BadRequest_FieldViolation{
				{Field: "url", Description: "url is required"},
			},
		})
		return detailed.Err()
	}
	return nil
}

Client — cmd/client/main.go

import (
	"fmt"

	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/grpc/status"

	"shortener/pb"
)

// Reading error details
resp, err := client.CreateLink(ctx, &pb.CreateLinkRequest{})
if err != nil {
	st := status.Convert(err)
	fmt.Printf("error: %s (%s)\n", st.Message(), st.Code())
	for _, detail := range st.Details() {
		if br, ok := detail.(*errdetails.BadRequest); ok {
			for _, v := range br.GetFieldViolations() {
				fmt.Printf("  field %s: %s\n", v.GetField(), v.GetDescription())
			}
		}
	}
}

💻 Run locally

Copy the code above and run it on your machine

© 2026 ByteLearn.dev. Free courses for developers. · Privacy