CodeGym /행동 /Go SELF /CLI error handling: details in errors and logs

CLI error handling: details in errors and logs

Go SELF
레벨 49, 레슨 4
사용 가능

1. Why a “wall of text” in CLI is bad UX

When we write a console utility, it seems that we can just do fmt.Fprintln(os.Stderr, err) and not worry about it. But a CLI has two features: first, people often read it (their eyes get tired), and second, scripts often read it (they do not like unpredictability). That is why a “wall of text” from internal details almost always makes things worse.

Imagine the difference between two messages.

Option A (bad):
error: open /Users/you/.config/tasker/tasks.json: permission denied

Option B (better):
error: cannot read tasks storage

Why is option B better? Because it answers the user’s question: “what should I do?” For example: check permissions, the path, or run with the needed access. But the absolute path, the internal file name, and the OS error type are details for diagnostics.

In Go, standard error wrappers often contain internal details (paths, operations, errno), and the Go authors themselves note separately: not everything from low-level errors should be “promised” to the outside as part of stable API behavior. In CLI, this idea is even more important: the error text is your user interface.

We need to learn to separate:

  • a short message for the user (one or two sentences, without technical guts);
  • the technical cause (in the wrapped error, so it can be diagnosed).

2. Two audiences for an error

It is useful to think that every error has two audiences. The first audience is the user, who wants to understand what to fix. The second audience is the developer (often you yourself two days later), who wants to understand where it broke, with what data, and what the root cause was. These audiences rarely want the same thing.

If you print everything you know to the user, you get a “wall of text.” If you print only “something went wrong,” you will not be able to figure it out later either. The compromise looks like this: we give a short message outward, and keep the details in the error chain and reveal them only at the application boundary (in logs, in debug mode, in tests).

In Go, this is a natural style: an error is a value that can be “packed” and passed upward, adding context. Wrapping works in the same style: we preserve the cause, but add the context of what was happening around it.

Let us make a small error type that stores both layers: “what to show the user” and “what to treat as the cause.”

package main

type UserError struct {
	msg string
	err error
}

func (e *UserError) Error() string { return e.msg }
func (e *UserError) Unwrap() error { return e.err }

Here is the important trick: Error() returns only the short message. And Unwrap() lets you “pull out” the internal cause if you need to analyze it or print it for diagnostics.

3. Print the error only once

If an error is printed at every layer (in the command, in the dispatcher, in main), the user gets three identical messages and starts suspecting the application is a little nervous. You need discipline: return error from below, print at the top.

From an architectural point of view, it looks like this: all functions like runAdd/runList/runDone return an error, the dispatcher returns an error, and main decides three things: what to print, which exit code to return, and where to call os.Exit.

The skeleton looks calm:

package main

import (
	"fmt"
	"os"
)

func main() {
	err := run(os.Args[1:])
	printUserError(err)
	os.Exit(exitCode(err))
}

func printUserError(err error) {
	if err == nil {
		return
	}
	fmt.Fprintln(os.Stderr, "error:", err)
}

Notice: here printUserError prints err as a string. But if we agree that our “nice” errors are *UserError, then the string will be exactly the short msg, not the whole technical story.

And one more reminder: os.Exit terminates the process immediately, so defer after it will not run. Because of this, keep os.Exit only at the very top level; otherwise, one day you will “lose” file closing or Flush().

4. Exit codes: usage vs fail

Earlier we agreed on exit codes: 0 /1 /2. Now we need to make it work not “by intuition,” but consistently. That is, so that we can programmatically distinguish “the user launched the command incorrectly” from “the command launched correctly, but something went wrong during execution.”

The simplest way is a sentinel error ErrUsage and a check via errors.Is. The idea: we do not analyze the text of the error (that almost always breaks), but ask: “Is ErrUsage present in the chain of causes or not?”

package main

import (
	"errors"
)

var ErrUsage = errors.New("usage")

const (
	exitOK    = 0
	exitFail  = 1
	exitUsage = 2
)

func exitCode(err error) int {
	if err == nil {
		return exitOK
	}
	if errors.Is(err, ErrUsage) {
		return exitUsage
	}
	return exitFail
}

Now we just need to learn how to create errors so that ErrUsage really ends up in the chain of causes, but the user still does not see the “internal mess.” For this, we will define a couple of small constructors.

package main

import "errors"

func usageError(msg string, cause error) error {
	return &UserError{
		msg: msg,
		err: errors.Join(ErrUsage, cause),
	}
}

func execError(msg string, cause error) error {
	return &UserError{
		msg: msg,
		err: cause,
	}
}

Here errors.Join is used: it lets you attach two causes to one error at once (the ErrUsage marker and a concrete cause, such as a parsing error). This is convenient because errors.Is(err, ErrUsage) will work, and the cause will not be lost.

The user, meanwhile, will see only msg, because Error() on UserError returns the short text.

5. Short messages, but useful

A short message does not mean “meaningless.” A good short message usually answers one of these questions: what exactly was expected, what exactly was received, and what can the user do next. And it almost always fits in one line.

For example, for the done command, which expects a numeric id, the message ID must be integer is much more useful than strconv.Atoi: parsing "abc": invalid syntax. The second message is technically more precise, but it is written for a developer, not for a user.

Let us see what this looks like in a handler with FlagSet. Here we deliberately create two “error branches”: a short one outward and a detailed one inward.

package main

import (
	"flag"
	"fmt"
	"strconv"
)

func runDone(argv []string) error {
	fs := flag.NewFlagSet("done", flag.ContinueOnError)
	if err := fs.Parse(argv); err != nil {
		return usageError("invalid flags", err)
	}
	if fs.NArg() != 1 {
		return usageError("usage: tasker done ID", nil)
	}

	idStr := fs.Arg(0)
	id, err := strconv.Atoi(idStr)
	if err != nil {
		return usageError("ID must be integer", fmt.Errorf("parse ID %q: %w", idStr, err))
	}

	_ = id
	return nil
}

Notice: the “details” are in fmt.Errorf("parse ID %q: %w", ...), and what goes outward is ID must be integer. The user quickly understands what to fix. And if you are figuring out what exactly was received, you already have idStr preserved in the cause.

In short CLI messages, it is useful to be a little less “literary” and a little more “instructional.” A console is not a novel; it is fine to speak directly here.

6. Edge case: “task not found”

There is one interesting edge case that almost always causes debate. Suppose the user ran tasker done 999, but there is no task with that ID. Is that a usage error or an execution error?

If the user typed tasker done abc, that is definitely usage: the argument type is wrong. But “there is no task” is no longer about the launch syntax, but about the state of the data. The command launched correctly, the flags and arguments are valid, but the action cannot be completed. Therefore it is logical to treat this as an execution error and return exit code 1.

To make this feel consistent, it is useful to keep the following table in mind:

Situation What we tell the user Which exit code
No command / flags did not parse / wrong number of arguments usage: ... or a short missing command 2
Argument type is wrong (ID is not a number) ID must be integer 2
No data (task not found) task not found 1
Internal failure (for example, reading storage, unexpected nil, I/O) cannot load tasks 1

This is not the only possible choice, but it is very practical: 2 means “restart correctly,” and 1 means “restarting will not necessarily help; the problem is in execution.”

Let us add a minimal “not found” error with a cause to our educational “tasker.”

package main

import "errors"

var ErrNotFound = errors.New("not found")

func markDone(id int) error {
	// suppose we search for a task by id inside
	found := false
	if !found {
		return execError("task not found", ErrNotFound)
	}
	return nil
}

The user will see “task not found.” And you can check errors.Is(err, ErrNotFound) in code (or in diagnostics) and, for example, distinguish “not found” from an “internal failure.”

7. Diagnostics without “walls of text”

Extracting the chain of causes without a logger

We have not connected logging as a full subsystem yet (and that is normal), but sometimes you want to see what is inside an error, especially when you are debugging the program yourself. The only important thing is not to turn this into default behavior; otherwise, the user will again get a “wall of text.”

Let us make a simple diagnostic printer that prints the chain of causes. You can enable it temporarily while debugging or keep it disabled in release builds.

package main

import (
	"errors"
	"fmt"
	"os"
)

func printDebugChain(err error) {
	for i := 0; err != nil; i++ {
		fmt.Fprintf(os.Stderr, "debug cause #%d: %v\n", i, err)
		err = errors.Unwrap(err)
	}
}

If your error is *UserError, then errors.Unwrap will go inside via Unwrap() and extract the technical cause. If the cause is wrapped further with %w, the chain continues.

In main, this can be used carefully: first we print a short message to the user, and then, for example, temporarily call debug printing.

package main

func main() {
	err := run(os.Args[1:])
	printUserError(err)

	if err != nil {
		// Temporary for development. In release builds it is usually disabled.
		printDebugChain(err)
	}

	os.Exit(exitCode(err))
}

Yes, this is crude. But it is honest: the user does not drown in details, and you do not lose the cause. In a real application, the role of printDebugChain is usually played by logs at the application boundary, but in essence it is the same: details go to diagnostics, not into the user’s face.

Mini-example: flag.FlagSet without double printing

flag.FlagSet by default likes to print its own messages, and if you do not control the output, you get “double printing”: first flag wrote something, then you printed error: .... Earlier we chose flag.ContinueOnError so that the parser returns an error instead of terminating the process, but it is still better to direct the output where you want it.

The idea is this: FlagSet writes diagnostic text to stderr, and we turn it into a short message.

package main

import (
	"flag"
	"os"
)

func runAdd(argv []string) error {
	fs := flag.NewFlagSet("add", flag.ContinueOnError)
	fs.SetOutput(os.Stderr)

	title := fs.String("title", "", "task title")
	if err := fs.Parse(argv); err != nil {
		return usageError("invalid flags", err)
	}
	if *title == "" {
		return usageError("missing -title", nil)
	}
	return nil
}

What matters: even if err contains a rather detailed text from flag, we do not show it to the user directly as the “main” message. The main message is ours, short. And err remains inside as the cause.

8. Common mistakes

Mistake #1: printing an error at every layer (“just in case”).
Usually it starts innocently: “I caught the error here, I’ll print it to see it.” Then another layer prints it too, then a third one — and in the end the user sees two or three identical error: lines in a row. The fix is discipline: below, only return err; printing happens only once at the application boundary.

Mistake #2: detecting a usage error by the text of the error.
It is very tempting to write something like strings.Contains(err.Error(), "usage") because it is “quick.” But this breaks with the slightest text refactor, with localization, and in general with a breeze in the neighboring office. Much more reliable: the sentinel error ErrUsage and an errors.Is check.

Mistake #3: showing technical details to the user instead of a message.
In Go, fmt.Errorf("...: %w", err) makes the error string “...: <cause text>.” If you print this error to the user as is, you again get a “wall of text” from internal details. The solution is to separate msg (outward) and cause (inward), for example via UserError.

Mistake #4: calling os.Exit inside a command handler.
This seems convenient: “oh, there is an error — I will exit immediately.” But then you cut yourself off from centralized printing, error classification, and, most importantly, you break defer (it will not run). So the command handler returns error, the dispatcher returns error, and only main calls os.Exit.

Mistake #5: making the message so short that it stops being useful.
The message error happened is indeed short, but it is useless. A good short text should still guide: missing command, usage: tasker done ID, ID must be integer, task not found. Short does not mean empty; short means without unnecessary internal details.

1
과제
Go SELF, 레벨 49, 레슨 4
잠금
종료 코드 맵
종료 코드 맵
1
과제
Go SELF, 레벨 49, 레슨 4
잠금
오류 한 줄
오류 한 줄
1
과제
Go SELF, 레벨 49, 레슨 4
잠금
사용자용 오류
사용자용 오류
1
과제
Go SELF, 레벨 49, 레슨 4
잠금
디버그가 포함된 카탈로그
디버그가 포함된 카탈로그
1
설문조사/퀴즈
flag.FlagSet을 사용한 하위 명령, 레벨 49, 레슨 4
사용 불가능
flag.FlagSet을 사용한 하위 명령
flag.FlagSet을 사용한 하위 명령
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION