CodeGym /コース /Go SELF /Exit codes: CLI のための 0/1/2 契約

Exit codes: CLI のための 0/1/2 契約

Go SELF
レベル 49, レッスン 3
使用可能

1. すでに error があるのに、なぜ CLI に exit code が必要なのか

コンソールプログラムを書き始めたばかりの頃は、「エラー!」というテキストを出せば十分だと思いがちです。ですが、あなたのユーティリティがサンドボックスの中だけで動くのをやめ、スクリプト、CI、cron、Docker エントリポイント、そして他のプログラムからも起動されるようになると、重要になるのは 何を表示するか だけではなく、プロセスがどう終了したか です。そこで exit code が登場します。

error は Go コードの 内部 では便利な仕組みです。上位へ返す、文脈を付けてラップする、errors.Is で分類する、人間に表示する。ですが、シェル(bash、PowerShell)やプログラムの外側の環境は error を読みません。彼らが見るのは整数だけです。「0 か、それ以外か」。でも私たちは、「全部だめ」以上の意味を少しだけ持たせたいのです。

その結果、CLI には外部向けの契約が生まれます。周囲の世界が「何が起きたか」をどの終了コードで理解するのか、という契約です。そしてこの契約は安定していなければなりません。メッセージの文言は変えてもよいですが、コードは予測可能であるべきです。そうしないと、未来のあなたのスクリプトが泣くことになります。

2. CLI の 0/1/2 契約

最小限ですが、とても実用的な標準を決めましょう。多くの CLI で見られますし、課題や採点でもこの形が期待されることがよくあります。つまり、3 つの結果、3 つのコードです。

Code Name (roughly) Meaning for the environment Typical reasons
0 success Command completed successfully all good
2 usage The user started the command incorrectly unknown command, invalid arguments, -h/-help, flag parsing error
1 failure The command started correctly, but could not do the work I/O error, "access denied", internal error

Why is 2 separate, and not also 1? Because "usage" does not mean "the program broke". It means "the user violated the launch contract". Scripts and shells often use this distinction, for example, to avoid retries when the problem is in the arguments, or to print help in a different way.

And there is another human-friendly advantage: 2 is a polite signal that says "try again, here is the correct way". And 1 says "you did everything right, but the world around us failed" (or we made a mistake in the code, which also happens, alas).

3. os.Exit and the defer nuance

As soon as we talk about exit codes in Go, we run into os.Exit(code). main() has no return value, so you cannot "return 2" directly. That means somebody has to call os.Exit.

But os.Exit has a personality, and it is rather sharp: it does not "return from the function"; it terminates the process immediately. That means all deferred calls (the ones you wrote with defer) do not run.

It is very easy to observe in practice:

package main

import (
	"fmt"
	"os"
)

func main() {
	defer fmt.Println("defer: I will NOT be printed")
	os.Exit(2)
}

If you run this, you will not see the line from defer. So the rule is almost like a law of physics: keep os.Exit only at the top level, and let all other code return error (or int via a separate function) so that defer-based cleanup works properly.

This is especially important when you have files, locks, buffered writers, and anything else that must be closed or flushed. Once you start using defer for real, "exit from deep inside" becomes your favorite source of weird bugs like "why is the file empty even though I definitely wrote to it?".

4. A single exit point: run → error → exitCode → os.Exit

Let's build an architecture that almost always turns out to be convenient in CLI programs. The idea is simple: let the business logic return an error, and compute the exit code in one place. That makes behavior predictable and removes "dancing" across the entire codebase.

Imagine the execution flow like this:

flowchart TD
    A[main] --> B["run(args) error"]
    B -->|err == nil| C[exit code 0]
    B -->|"errors.Is(err, ErrUsage)"| D[exit code 2]
    B -->|otherwise| E[exit code 1]
    C --> F["os.Exit(code)"]
    D --> F
    E --> F

The key point: run(...) does not call os.Exit. It simply returns error. That means inside run and inside command handlers you can safely use defer for cleanup — everything will run.

Here is the Go skeleton code (short and to the point):

package main

import "os"

func main() {
	code := realMain(os.Args[1:])
	os.Exit(code)
}

And here is the logic: printing errors, translating error → exit code:

package main

import (
	"fmt"
	"os"
)

func realMain(args []string) int {
	err := run(args)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		return exitCode(err)
	}
	return exitOK
}

Notice that we print the error before os.Exit. This matters because after os.Exit, it is too late to print anything (the process is gone).

5. Naming codes: no more "magic 1 and 2"

The next step is to stop scattering "1" and "2" throughout the code. First, it is easier to read. Second, it is harder to make a mistake: you will not confuse where usage is and where fail is.

package main

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

Now exitCode(err) can be very compact:

package main

import "errors"

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

Here we use errors.Is to determine the class of the error. The important thing is that errors.Is works not only with "plain" errors, but also with wrapped ones — that is, if you added context via %w, the check will still walk the chain. This is exactly how the standard library recommends classifying errors through a "chain of causes".

6. ErrUsage and the usagef helper

For exitCode to work based on meaning rather than on the error text, we need a stable marker. Usually this is a sentinel error: one variable ErrUsage, and we wrap it into all incorrect-launch errors.

package main

import "errors"

var ErrUsage = errors.New("usage")

Why is this good? Because error text is fragile. Today you write missing command, tomorrow you change it to command is required, and suddenly someone's code that did strings.Contains(err.Error(), "missing") breaks. But errors.Is(err, ErrUsage) does not depend on the text and is designed exactly for such scenarios.

Let's make a small helper so it is convenient to create usage errors:

package main

import "fmt"

func usagef(format string, args ...any) error {
	return fmt.Errorf("%w: "+format, append([]any{ErrUsage}, args...)...)
}

Yes, the line looks a bit "magical", but in essence it does something simple: it adds ErrUsage as the first argument and formats the message. You get both classification and human-readable text.

7. Usage errors in a CLI with subcommands

Now let's connect this to our application (let it be a training todo/tasker) that already knows how to choose a subcommand and pass argv to it.

The subcommand dispatcher usually handles two usage situations: no command provided and unknown command. This is a usage error, so we return usagef(...).

package main

func run(args []string) error {
	if len(args) == 0 {
		return usagef("missing command")
	}

	switch args[0] {
	case "add":
		return runAdd(args[1:])
	case "list":
		return runList(args[1:])
	default:
		return usagef("unknown command: %s", args[0])
	}
}

Notice an important style point: run does not print, does not call os.Exit, and does not decide "what to do with the user". It simply reports upward: "this is usage" or "this is runtime".

And a command handler can return either a usage error (for example, invalid arguments) or a normal runtime error (for example, could not write a file). That distinction will then automatically become 2 or 1.

Flag parsing errors are almost always exitUsage

Let's take the add command. Suppose it accepts a -title flag and does not accept positional arguments (for simplicity). We create a FlagSet in flag.ContinueOnError mode so that Parse() returns an error instead of terminating the process on its own.

package main

import (
	"flag"
	"fmt"
)

func runAdd(argv []string) error {
	fs := flag.NewFlagSet("add", flag.ContinueOnError)
	title := fs.String("title", "", "task title")

	if err := fs.Parse(argv); err != nil {
		return usagef("%v", err)
	}

	if *title == "" {
		return usagef("missing -title")
	}

	fmt.Println("added:", *title) // added: Buy milk
	return nil
}

The important idea here is that an "invalid flag" is not "the program broke". It is the user typing -tittle instead of -title (a classic). Therefore the return code should be 2, and we achieve that by wrapping with ErrUsage.

Why you should not call os.Exit inside runAdd

Sometimes there is a temptation: "Well, the error is already here, why wait? I'll do fmt.Fprintln(os.Stderr, ...) and os.Exit(2) right in runAdd." At short range it looks simpler. At long range, you get two problems.

The first problem is that defer will not run. This hurts especially when later you add file writes, buffering, temporary files, locks. You opened a file, added defer f.Close(), and then somewhere in the middle called os.Exit: the file may not close, buffers may not flush, the lock may not release.

The second problem is that the code becomes fragmented: some errors are printed in one place, some in another. As a result, you can accidentally print an error twice, or forget to print it at all. A single output point is like a single metro entrance: there may be a queue, but nobody jumps over the turnstiles.

So the adult rule is: all functions except the topmost level return errors, they do not terminate the process.

8. Printing errors: stdout vs stderr

Since we already have a single exit point, it is logical that we print errors there as well. The usual policy is: everything that is the "result of the command" goes to stdout, and everything that is diagnostics goes to stderr.

In our skeleton this is already reflected:

fmt.Fprintln(os.Stderr, "error:", err)

This is useful because the user can do:

  • app list > out.txt and get a clean task list without noise,
  • while still seeing errors in the terminal.

Another subtle point: do not turn an error message into a 20-line novel. The message should be short and clear. Technical details are often better left "inside" the chain of errors, while the outside prints one compact text. (We are not turning on logging and debug modes here yet — we are just establishing basic hygiene.)

9. A minimal tasker skeleton with 0/1/2 codes

Below is a skeleton that ties the ideas into one scheme. It does not implement real task storage yet (which is fine), but it shows where exit codes live.

package main

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

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

var ErrUsage = errors.New("usage")

func main() {
	code := realMain(os.Args[1:])
	os.Exit(code)
}

func realMain(args []string) int {
	err := run(args)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		return exitCode(err)
	}
	return exitOK
}

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

And here is run(...), which for now only knows how to "recognize" commands:

package main

func run(args []string) error {
	if len(args) == 0 {
		return usagef("missing command")
	}

	switch args[0] {
	case "add":
		return runAdd(args[1:])
	case "list":
		return runList(args[1:])
	default:
		return usagef("unknown command: %s", args[0])
	}
}

Plus a helper:

package main

import "fmt"

func usagef(format string, args ...any) error {
	return fmt.Errorf("%w: "+format, append([]any{ErrUsage}, args...)...)
}

And a command stub (so it builds):

package main

import "fmt"

func runList(argv []string) error {
	_ = argv
	fmt.Println("no tasks yet") // no tasks yet
	return nil
}

Now the behavior by codes will be like this: tasker list returns 0, tasker without a command returns 2, and any "real" runtime errors (when they appear later) will return 1.

10. Typical mistakes

Mistake #1: calling os.Exit inside command handlers.
At first this seems convenient: the error is nearby, so the "exit" can be nearby too. But this breaks deferred cleanup and turns the program into a set of inconsistent "death points". As a result, some errors are printed twice, some are not printed at all, and resources sometimes remain unclosed. It is better to return error upward and terminate the process in one place.

Mistake #2: relying on defer after os.Exit has already been called.
defer runs on normal function return. os.Exit does not return from the function — it terminates the process. Therefore any defer "after os.Exit" will not run. The reliable pattern is a separate realMain that does all the work, and main that only calls os.Exit with the code returned by realMain.

Mistake #3: mapping all errors to code 1.
If you do not separate usage errors from runtime errors, your users and scripts lose important information. Invalid arguments, unknown commands, and flag parsing errors are exitUsage = 2. Network, file, and "internal" errors are exitFail = 1. This separation makes the CLI much more automation-friendly.

Mistake #4: determining usage by the error text.
Checks like strings.Contains(err.Error(), "usage") may seem like a quick fix, but they break with the slightest refactoring of the text. It is much more reliable to have the ErrUsage marker and check it via errors.Is. This is exactly the standard mechanism for semantic error classification in Go.

Mistake #5: printing errors in every layer.
When both runAdd, the dispatcher, and main print errors, the user gets a nested set of messages. Sometimes this turns into three identical error: ... lines. It is cleaner to print once at the top level and only return error below, adding context via wrapping when needed.

1
タスク
Go SELF, レベル 49, レッスン 3
ロック未解除
三つの結果
三つの結果
1
タスク
Go SELF, レベル 49, レッスン 3
ロック未解除
Usage センチネル
Usage センチネル
1
タスク
Go SELF, レベル 49, レッスン 3
ロック未解除
フラグ付き Repeat
フラグ付き Repeat
1
タスク
Go SELF, レベル 49, レッスン 3
ロック未解除
コードとエラー
コードとエラー
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION