1. Application boundary: where an error becomes "human"
If you have ever seen a program that proudly writes to the user panic: runtime error: invalid memory address, then you understand: the "user interface of errors" can be... very honest. And we need a different kind of honesty: inside the code we want the most precise cause possible, and outside — a clear and stable message. This is the place where the "inner world" meets the "outer world", and it is called the boundary.
By boundary I will mean any layer that communicates with the outside world: CLI (command line), HTTP API, sometimes UI, sometimes file import/export. Internal layers (domain/app) must not know how exactly we communicate with the user. Otherwise the domain starts printing to the console, and scenarios start deciding HTTP statuses — and the architecture turns into a salad.
Let us imagine our training application: a small todo manager. Inside we have the domain model Task, the scenarios Add/Get, a storage adapter (for now in-memory), and a very simple CLI entry point. Today we will learn how to make errors pass through the layers neatly: the meaning is preserved, and the form changes only at the boundary.
2. Domain errors: meaning is more important than text
When we say "domain error", we usually mean not "something broke", but "a forbidden state occurred from the point of view of the business domain". For example, a task cannot have an empty title. This is not a console or HTTP problem — it is a rule of our todo world.
It is important to keep one idea in mind: branching on errors should happen by meaning, not by string. A string is what people read. And the code should rely on distinguishable values: sentinel errors or typed errors and checks through errors.Is/errors.As. In Go this is directly supported through errors.Is and errors.As, which can "see" an error even inside a chain of wrappers (error chain).
Sentinel errors in the domain
Let us start with the simple thing: several "marker" errors in the domain.
// domain/errors.go
package domain
import "errors"
var ErrEmptyTitle = errors.New("empty title")
var ErrNotFound = errors.New("not found")
ErrEmptyTitle and ErrNotFound are not "messages for the user", but identifiers of meaning: "title is empty", "object not found". The text also matters, but its job is to be useful during debugging and in logs.
Typed validation error
When there are more rules, we want not just to say "validation failed", but also to attach details: which field, what is wrong. This is a classic case for a typed error.
// domain/validation.go
package domain
type ValidationError struct {
Fields map[string]string
}
func (e *ValidationError) Error() string {
return "validation failed"
}
Here Fields is a data structure for code, and Error() is a short string for people. Yes, it is very boring — that is normal: we do not want to build a UI out of Error().
And yes, this is the case where later at the boundary (CLI/HTTP) we will retrieve Fields through errors.As.
Invariants: create an entity or return an error
The domain is the place where we preserve invariants. That is, we either create a correct Task, or we honestly say "not allowed".
In our todo application let Task be created through a constructor:
// domain/task.go
package domain
type Task struct {
ID int
Title string
Done bool
}
func NewTask(id int, title string) (Task, error) {
if title == "" {
return Task{}, ErrEmptyTitle
}
return Task{ID: id, Title: title, Done: false}, nil
}
Pay attention to an important style: we return the zero value (Task{}) together with the error. No "half-built" entities. This makes the code above in the layers simpler: if err != nil, the object cannot be used — period.
If there were more rules, we could return *ValidationError with fields:
// domain/task.go (variant, if we want fields)
package domain
func NewTask(id int, title string) (Task, error) {
fields := make(map[string]string)
if title == "" {
fields["title"] = "must not be empty"
}
if len(fields) > 0 {
return Task{}, &ValidationError{Fields: fields}
}
return Task{ID: id, Title: title, Done: false}, nil
}
This variant is especially convenient for a future HTTP API, but it is already useful for the CLI: you can show the user exactly what they entered incorrectly.
3. Errors through layers: add context, preserve meaning
Now the scenario layer (app) — the one that "orchestrates" the steps: get an ID, create a task, save it. Here it is very easy to make two typical mistakes: either lose the context ("where exactly did it fail?"), or lose the meaning ("why did it fail?"). Our goal is to preserve both.
Go directly pushes us toward wrapping with %w: this way the error remains "unwrappable" for errors.Is/errors.As.
The dependency interface is declared by app, not by the adapter
The scenario needs not to know which storage we have (memory, file, database), so it accepts an interface.
// app/store.go
package app
import (
"context"
"example.com/todoapp/domain"
)
type TaskStore interface {
NextID(ctx context.Context) (int, error)
Save(ctx context.Context, t domain.Task) error
}
Add-task scenario with wrapping
// app/add.go
package app
import (
"context"
"fmt"
"example.com/todoapp/domain"
)
func AddTask(ctx context.Context, store TaskStore, title string) (domain.Task, error) {
id, err := store.NextID(ctx)
if err != nil {
return domain.Task{}, fmt.Errorf("next id: %w", err)
}
t, err := domain.NewTask(id, title)
if err != nil {
return domain.Task{}, err
}
if err := store.Save(ctx, t); err != nil {
return domain.Task{}, fmt.Errorf("save task: %w", err)
}
return t, nil
}
There is a small philosophy here.
We wrap dependency errors (NextID, Save) — because above it is useful to know at which step it failed.
We are not obliged to wrap domain errors (for example ErrEmptyTitle): they are already "our level". But sometimes wrapping is also fine — if you preserve the meaning through %w and do not turn the text into a contract.
Wrapping is part of the API decision
And here a subtle point appears. Wrapping makes the error "visible" to the code above: errors.Is(err, X) can find X inside the chain. That is great... until you accidentally start leaking internal adapter errors outward (for example, sql.ErrNoRows), thereby promising the world: "we will always use exactly this database and exactly this error."
In the official discussions of errors in Go, the formulation is usually straightforward: if you wrap someone else's error and give code above the ability to rely on it through unwrap, you make it part of the API — and then it becomes harder to change the implementation.
For our day this means: domain errors can be made part of the contract, while errors from specific technologies — it is better to "translate" them into domain errors (or into layer errors), so that the details do not stick out to the outside world.
4. Adapter: translating technical problems into meaningful ones
Adapters are the place where technical reality meets our domain. Even if today we have a simple in-memory storage, the style is already set up the same way as for more serious stores: the adapter may return domain.ErrNotFound if the record does not exist.
Let us make a minimal memstore:
// adapters/memstore/store.go
package memstore
import (
"context"
"example.com/todoapp/domain"
)
type Store struct {
next int
data map[int]domain.Task
}
func New() *Store {
return &Store{next: 1, data: make(map[int]domain.Task)}
}
And now the methods. Try to keep them simple, without overengineering.
// adapters/memstore/save.go
package memstore
import (
"context"
"example.com/todoapp/domain"
)
func (s *Store) NextID(ctx context.Context) (int, error) {
id := s.next
s.next++
return id, nil
}
func (s *Store) Save(ctx context.Context, t domain.Task) error {
s.data[t.ID] = t
return nil
}
And here is an example of reading with "not found":
// adapters/memstore/get.go
package memstore
import (
"context"
"example.com/todoapp/domain"
)
func (s *Store) ByID(ctx context.Context, id int) (domain.Task, error) {
t, ok := s.data[id]
if !ok {
return domain.Task{}, domain.ErrNotFound
}
return t, nil
}
Here the adapter does not say "map key missing" (because that has nothing to do with the domain meaning). It says "not found" in the language of the domain.
5. CLI boundary: message and exit code
CLI is a special boundary. It loves concreteness: what to write to the user, where to write it (stdout or stderr), and which exit code to return. At the same time the CLI should not dissect the "internals" of the application by error strings — only by meaning through errors.Is/errors.As.
One of the most useful techniques in Go (and in life in general) is to move error formatting into a separate function: WriteError(...) or RenderError(...). This keeps main short, and the logic does not get smeared across the project.
Mini correspondence table
Let us make an agreement. For now, without complex standardization, just a reasonable minimum.
| Error meaning | What to show the user | Where to print | Exit code |
|---|---|---|---|
| validation | "Invalid input: ..." | stderr | 2 |
| not found | "Not found: ..." | stderr | 1 |
| other | "Internal error" | stderr | 1 |
Yes, this table will still evolve, but the idea itself is more important: the boundary decides the form, and the internal layers decide the meaning.
Rendering an error for the CLI through errors.Is/As
// boundary/cli/errors.go
package cli
import (
"errors"
"fmt"
"io"
"example.com/todoapp/domain"
)
func WriteError(w io.Writer, err error) int {
var ve *domain.ValidationError
if errors.As(err, &ve) {
fmt.Fprintln(w, "invalid input:", ve.Fields) // invalid input: map[title:must not be empty]
return 2
}
if errors.Is(err, domain.ErrNotFound) {
fmt.Fprintln(w, "not found") // not found
return 1
}
fmt.Fprintln(w, "internal error") // internal error
return 1
}
Pay attention to errors.As(err, &ve). Here we pass the address of the variable so that the function can "write the found error" into it — this is the standard errors.As contract.
And one more detail: we do not print err.Error() to the user in "other" cases. Why? Because err may contain anything: storage details, file paths, internal hints for the developer. The user is usually not happy with that, and sometimes it is also unsafe.
main.go example: a minimal skeleton
Let us make a super-simple CLI without flag (we will discuss it separately in another part of the course). Let the command be: todoadd <title>.
// cmd/todo/main.go
package main
import (
"context"
"fmt"
"os"
"example.com/todoapp/adapters/memstore"
"example.com/todoapp/app"
"example.com/todoapp/boundary/cli"
)
func main() {
store := memstore.New()
title := ""
if len(os.Args) >= 2 {
title = os.Args[1]
}
t, err := app.AddTask(context.Background(), store, title)
if err != nil {
code := cli.WriteError(os.Stderr, err)
os.Exit(code)
}
fmt.Println("added:", t.Title) // added: buy milk
}
The main thing here is the structure of thought: main should not "think" about error types. It delegates this to the cli boundary.
6. HTTP boundary: same meaning, different form
HTTP is the same story, only the form is different. There the user is often not a person, but a script or a frontend client. It needs to understand reliably: is this a validation error? not found? internal? Therefore the HTTP boundary usually returns a "structured" error: status code + JSON (or at least an error code).
Today we are not building an HTTP server, but we can (and should) prepare a function for converting an error into an HTTP response. Later it will be used in handlers.
By the way, moving error handling into one place for HTTP is normal practice in Go: instead of repeating if err != nil { ... } in every handler, they make a common layer that accepts error and decides what to send outward.
Structure of an error response
// boundary/httpx/errors.go
package httpx
type ErrorResponse struct {
Status int
Code string
Message string
Fields map[string]string
}
This is not net/http and not real JSON — it is just a structure that can easily be encoded later. The important idea: Message is for the outside world, Code is for machines, Fields is for validation.
Mapping errors to an HTTP response
// boundary/httpx/map.go
package httpx
import (
"errors"
"example.com/todoapp/domain"
)
func ToErrorResponse(err error) ErrorResponse {
var ve *domain.ValidationError
if errors.As(err, &ve) {
return ErrorResponse{Status: 400, Code: "validation", Message: "bad request", Fields: ve.Fields}
}
if errors.Is(err, domain.ErrNotFound) {
return ErrorResponse{Status: 404, Code: "not_found", Message: "not found"}
}
return ErrorResponse{Status: 500, Code: "internal", Message: "internal error"}
}
We use errors.As and errors.Is again. That is, our "universal engine" is the domain's semantic errors and checking through the chain.
If later in the app layer we wrapped the error as fmt.Errorf("get task: %w", domain.ErrNotFound), the boundary still recognizes ErrNotFound, because errors.Is walks the chain.
What to propagate upward, and what is better to hide
It is very tempting to do this: "if os.Open returned an error — just wrap %w and pass it upward". Sometimes that is correct. But sometimes with this decision you accidentally promise implementation details to the outside world.
I will phrase it practically: wrapping is not just "to make it prettier", wrapping is a way to tell the code above: "you can rely on this". If you gave the ability to unwrap someone else's error, you are, in a sense, signing that it is part of your API, and you cannot painlessly change the technology later.
In our todo application this means the following.
If the adapter "did not find the record", it should return domain.ErrNotFound, not "some map error" and not a "database error". Then domain.ErrNotFound becomes that semantic anchor understood by both CLI and HTTP.
If the adapter received an unexpected technical error (for example, "the file did not open"), the app layer can wrap it with context ("save task: %w"), and the boundary can show the user "internal error", while the log (or printing err for the developer) will contain the chain of causes.
And this is where the main balance emerges: for a person debugging, it is useful to see everything, while for the user — only what is understandable. That is exactly the meaning of "errors at the boundaries".
7. Typical mistakes
Mistake #1: comparing errors by string (err.Error() == "not found").
This seems like a quick solution, but it turns text into a contract, and text almost always changes: you will add context, tweak the wording, localize the message — and suddenly the branching logic will break. Instead, use errors.Is for sentinel errors and errors.As for typed errors, to branch by meaning.
Mistake #2: wrapping without %w where meaning matters.
If you write fmt.Errorf("save task: %v", err), then to a person it looks fine, but for the program the chain of causes is lost: errors.Is/errors.As will no longer be able to find the original domain error. If you rely on meaning recognition at the boundary — use %w.
Mistake #3: leaking implementation details through wrapping.
Sometimes a developer does "as the book says": %w everywhere, everything is "correct". And then it turns out that the upper layer started checking errors.Is(err, sql.ErrNoRows) or some other error from a specific library. This binds your code to a particular technology and makes refactoring painful. Where the technology is an internal detail, it is better to "translate" the error into a domain one (for example, domain.ErrNotFound) and expose that instead.
Mistake #4: the domain prints errors or chooses the exit code.
This is one of the most destructive habits: "I will just fmt.Println here so it is visible." In a couple of weeks the domain starts depending on fmt, scenarios depend on os.Exit, and testing everything becomes sad. Keep a hard rule: the domain and app return error, and the boundary decides what to do with it and what it looks like to the user.
Mistake #5: the boundary shows the user err.Error() for any error.
Inside an error there may be too much unnecessary stuff: internal paths, technical details, sometimes even pieces of configuration. It does not help the user, and sometimes it is harmful. A normal style is this: at the boundary you recognize the meaning (validation/notfound/internal) and show a stable message, while the full error is left for the logs/developer diagnostics.
GO TO FULL VERSION