Skip to content

Send an error to another process

errors/wire encodes an error so a process on the other side of an HTTP call, a queue or a gRPC stream gets it back with its sentinel identity, hints, details, attributes and kind intact.

import "gitlab.com/phpboyscout/go/errors/wire"

Encode and decode with one format

body, err := wire.Marshal(err, wire.JSON)

// in the other process
decoded, err := wire.Unmarshal(body, wire.JSON)

decoded is an error that answers every reader as the original did:

errors.Is(decoded, forge.ErrProviderNotFound)   // true: the same instance
errors.Hints(decoded)                           // the sender's hints
errors.KindOf(decoded)                          // the sender's kind
decoded == context.Canceled                     // true, when that is what was sent

Unmarshal returns two errors. The first is the decoded one. The second says whether decoding worked, and is never the sender's error.

Let the edge choose the format

An error does not know which boundary it will cross. The code where it leaves does, so build an encoder there once, listing the formats you offer, default first. errorsprotobuf.Codec below is the protobuf codec from the errors-protobuf module, which is still to ship; any wire.Codec goes in the list the same way.

var enc = wire.NewEncoder([]wire.Codec{wire.JSON, errorsprotobuf.Codec})

func writeError(w http.ResponseWriter, r *http.Request, err error, status int) {
    body, mediaType, encErr := enc.Encode(err, r.Header.Get("Accept"))
    switch {
    case errors.Is(encErr, wire.ErrNotAcceptable):
        http.Error(w, fmt.Sprint(err), http.StatusNotAcceptable)
        return
    case encErr != nil:
        // A nil err (ErrNil), or one past the encoder's bounds: plain text.
        http.Error(w, fmt.Sprint(err), status)
        return
    }
    w.Header().Set("Content-Type", mediaType)
    w.WriteHeader(status)
    _, _ = w.Write(body)
}

Encode reads the Accept value as HTTP defines it, with wildcards and q weights. An empty one gets the default. When nothing you offer is acceptable it returns wire.ErrNotAcceptable and no body, and what to send instead is your call.

On the receiving side, decode by the media type the sender declared:

readers := wire.NewReaders([]wire.Codec{wire.JSON, errorsprotobuf.Codec})

decoded, err := readers.Decode(resp.Header.Get("Content-Type"), body)

Send the stack, when you trust the receiver

Stacks are off by default: a stack names your functions and files, and the process on the other side is often outside your trust boundary. Turn them on for one call:

body, mediaType, err := enc.Encode(err, accept, wire.WithStacks())

The receiver reads them with errors.RemoteFrames, and %+v prints them under REMOTE STACK:. File paths are module-relative, never your build machine's.

Make your own sentinels and wrappers survive

A sentinel built with errors.NewSentinel and a namespaced kind registers itself when its package initialises. A receiver that links that package decodes it to the instance itself; one that does not gets an opaque leaf with the same message and kind. For a leaf you did not build that way, register it once:

func init() { wire.RegisterLeaf("myapp.no_rows", sql.ErrNoRows) }

A wrapper type of your own decodes as an opaque layer: message, kind and everything below it kept, and re-encoded exactly by a process that relays it. To get your type back, register a wire.LayerCodec for its kind:

wire.RegisterLayer("myapp.exit_code", exitCodeCodec{})

Check nothing collides

Two registrations under one kind, or a kind under errors. or std., which are reserved, cannot decode to what was registered. wire.Conflicts lists them. Assert it is empty in a test in your main package:

func TestNoWireConflicts(t *testing.T) {
    if c := wire.Conflicts(); len(c) > 0 {
        t.Fatalf("wire kind conflicts: %v", c)
    }
}

Bound what you accept

Decoding treats its input as untrusted and fails rather than truncate. The defaults are generous; lower or raise them for every call or for one:

readers := wire.NewReaders(codecs, wire.WithMaxInputBytes(64<<10))

The wire reference lists each bound and error.