CodeGym /행동 /Go SELF /File error classes — not exist, permission, invalid path

File error classes — not exist, permission, invalid path

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

1. Why split file errors into classes

파일을 다루기 시작하면, 문제를 만났을 때의 첫 반응은 보통 “아, 안 열렸네 — 그냥 넘어가자”처럼 보입니다. 하지만 아주 빨리 왜 안 열렸는지가 사실상 더 중요하다는 걸 알게 됩니다. 파일이 존재하지 않을 수도 있고(첫 실행이라면 정상일 수 있음), 권한 문제가 있을 수도 있으며(이 경우에는 사용자에게 설명해야 함), 아예 경로가 잘못되었을 수도 있습니다(입력값이나 설정을 고쳐야 하는 신호).

Go에서는 오류를 텍스트(err.Error())로 “판별”하는 것이 매우 좋지 않습니다. 텍스트는 OS, 로케일, 그리고 구체적인 시스템 호출에 따라 달라지기 때문입니다. 언어의 중요한 아이디어는 오류가 단순한 문자열이 아니라 값이며, 종종 구조화된 정보를 담고 있다는 점입니다. 그래서 우리는 오류의 class(not exist / permission / invalid path)를 “감으로”가 아니라 프로그램적으로 판별하는 법을 배웁니다.

참고용으로는 아래의 간단한 표를 머릿속에 두면 좋습니다:

Error class What it means in plain terms Typical program action
not exist
“The file/directory does not exist” Create the file/directory or accept the “empty state”
permission
“No rights to read/write” Show a clear message and suggest the path/permissions
invalid path
“The path is invalid” Fix input data/config, not “retry”

2. The not exist class: the file is missing — and that is often normal

“Does not exist” is the friendliest of file errors. It often means not a disaster, but that the program is running for the first time, the data has not been created yet, the directory does not exist, or the user specified the wrong path. It is important to learn to distinguish this scenario from “something serious broke,” because the reaction should be different.

In Go, there is a convenient check for this: os.IsNotExist(err). It works even if the error is wrapped in several layers, provided you wrapped it with %w. This directly supports the idea: “add context, but do not break cause detection.”

Mini example: “if the file is missing, treat the task list as empty”

Below is a small fragment for our educational app “mini-todo”, where tasks are stored in a file (one task per line). If the file is missing, we return an empty list and a nil error.


package main

import (
	"os"
)

func loadTasks(path string) ([]byte, error) {
	b, err := os.ReadFile(path)
	if err != nil && os.IsNotExist(err) {
		return []byte{}, nil
	}
	return b, err
}

Notice the style: we do not say “there is no error”; we say “the error is expected and is interpreted as empty data.”

3. The permission class: “the file exists, but you are not allowed”

Permission errors are usually more painful, because the program seems to be doing everything correctly, the file seems to exist, but the OS says: “no.” And that makes sense: the operating system protects data. In practice the reason may be trivial (running without the required rights, the file belongs to another user, the directory is read-only), but for the user it always looks like “your program broke.”

In Go, this class is easy to check with os.IsPermission(err). The idea is not to write “something went wrong,” but to give the person a clear message: “no permission to read/write at path …”. Technical details can stay in the wrapped error, but outwardly (especially in CLI tools) it is worth showing a short, direct message.

Mini example: a write attempt and a polite message

package main

import (
	"fmt"
	"os"
)

func saveTasks(path string, data []byte) error {
	err := os.WriteFile(path, data, 0644)
	if err != nil && os.IsPermission(err) {
		return fmt.Errorf("no permission to write file %q: %w", path, err)
	}
	return err
}

Here we do two things at once: we distinguish the permission class and add context (which file, which operation). This “two-layer” approach is normal in Go: clear context outside, recognizable cause inside.

4. The invalid path class: subtle, but important

With invalid path, there is bad news: unlike not exist and permission, it is not always recognized by one universal function such as os.IsInvalidPath. The reason is simple: what counts as an “invalid path” depends on the OS and the file system. Some systems forbid one set of characters, others forbid another; somewhere a path may be “too long,” elsewhere it may contain an invalid sequence.

But there is also good news: at the very least, you should be able to understand that the problem is in the path, and not try to fix it by creating directories, retries, or other magic. invalid path is usually a bug in input data/configuration, not a temporary failure.

A practical “rock-solid” example of an invalid path: \x00

There is one trick that works almost the same everywhere: a null byte in the path (\x00). It is invalid for system calls.

package main

import (
	"fmt"
	"os"
)

func main() {
	_, err := os.ReadFile("\x00")
	fmt.Printf("err=%v\n", err) // err=open <...>: invalid argument (wording depends on OS)
}

The text will differ across systems, and that is normal. The main idea is that even if it looks like “a path is just a string,” the OS treats it as a strictly limited format.

5. Why you should not compare errors by err.Error()

The temptation is understandable: “I can see the text permission denied, so I’ll just check strings.Contains.” The problem is that this breaks as soon as you change the environment. On another OS, the text is different. On the same OS, but for a different operation, it can also be different. Even the format may differ: sometimes the path is included in the message, sometimes it is not.

Go actively nudges you to work with errors as values: wrap them for context and check the cause using errors.Is/errors.As or the functions os.IsNotExist/os.IsPermission. This is one of the basic engineering habits in the Go ecosystem.

To “see” the correct order of actions, it helps to imagine the following processing protocol:

flowchart TD
    A["Perform a file operation (ReadFile/WriteFile/OpenFile)"] --> B{err == nil?}
    B -->|yes| C["Continue working"]
    B -->|no| D{"os.IsNotExist(err)?"}
    D -->|yes| E["Scenario 'first run': empty data / create directory"]
    D -->|no| F{"os.IsPermission(err)?"}
    F -->|yes| G["User message: no permissions + path"]
    F -->|no| H["Treat as unexpected error: wrap and return upward"]

6. Useful nuances: *os.PathError and wrapping with %w

When you print an error from os.ReadFile or os.Open, it often looks as if it already contains everything: operation, path, cause. But for the program this is also important: sometimes you want not just to print “error,” but to understand which operation failed (open, read, stat), with which path, and what cause lies inside.

For this, Go often uses the structured error *os.PathError. It stores the fields Op, Path, Err. And the nice part is that even if you wrapped the error with %w, you can still extract *os.PathError via errors.As. This is a direct continuation of “errors as values, not strings.”

Mini example: extracting PathError for diagnostics

package main

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

func main() {
	_, err := os.ReadFile("no_such_file.txt")
	if err == nil {
		return
	}

	var pe *os.PathError
	if errors.As(err, &pe) {
		fmt.Println(pe.Op)   // open
		fmt.Println(pe.Path) // no_such_file.txt
		fmt.Println(pe.Err)  // specific cause (depends on OS)
	}
}

This is not about “pretty output for the user,” but about diagnostics: as a developer, you quickly understand what exactly happened.

When you write file-handling code, you almost always need to return the error upward with a “human explanation”: what you were doing and with which path. And it is easy to shoot yourself in the foot here: if you wrap the error with %v, cause detection breaks; if you wrap it with %w, detection is preserved, but details of the internal error may “leak” outward.

In application code, especially in apps, it is usually useful to preserve the cause so that the upper level can make a decision. That is exactly what %w does. This “context outside, cause inside” model is standard in modern Go.

Mini example: “correct” wrapping

package main

import (
	"fmt"
	"os"
)

func load(path string) ([]byte, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("load todo file %q: %w", path, err)
	}
	return b, nil
}

If later you call os.IsNotExist(err) or errors.Is(err, os.ErrNotExist), it will keep working.

7. Example: mini-todo with error classification

Now let’s combine the ideas into one small scenario. Suppose we have a file data/todo/items.txt. Our program tries to read tasks and then, for simplicity, just prints how many tasks were found. We want:

  • if the file is missing, it should count as an empty list;
  • if there is no permission, we should say so in plain language;
  • if the path is invalid, we should not pretend that “the file is just missing.”

Step 1: reading with classification

package main

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

func readTodoFile(path string) ([]byte, error) {
	b, err := os.ReadFile(path)
	if err == nil {
		return b, nil
	}
	if os.IsNotExist(err) {
		return []byte{}, nil
	}
	if os.IsPermission(err) {
		return nil, fmt.Errorf("no permission to read %q: %w", path, err)
	}
	return nil, fmt.Errorf("failed to read %q: %w", path, err)
}

func main() {
	_, err := readTodoFile("data/todo/items.txt")
	if err != nil && errors.Is(err, os.ErrPermission) {
		fmt.Println("permission problem") // branch example (details above)
	}
}

Yes, we slightly “overprotect” ourselves in main, but that is normal for a teaching example: we are showing that wrapping preserves the cause.

Step 2: human-readable reaction without a “wall of text”

Below is an example of a function that turns a technical error into a short message. It is important not to go to extremes: do not hide the error completely, but also do not overwhelm the user with a three-screen stack trace.

package main

import (
	"fmt"
	"os"
)

func formatFileError(path string, err error) string {
	if os.IsNotExist(err) {
		return fmt.Sprintf("file or directory not found: %s", path)
	}
	if os.IsPermission(err) {
		return fmt.Sprintf("no permission to access file: %s", path)
	}
	return fmt.Sprintf("file operation error for %s: %v", path, err)
}

Here we intentionally keep the third branch generic. Why? Because invalid path and many other causes may look different, and our goal is to give the user a clear result without pretending we classified everything perfectly.

8. Typical mistakes

Mistake #1: checking common file problems via err.Error() and strings.Contains.
This code seems to work right up until the first OS change or the first time the error text looks different. It is much more reliable to think in classes: os.IsNotExist, os.IsPermission, and for diagnostics — errors.As(err, &pe) to *os.PathError.

Mistake #2: wrapping an error with %v and then wondering why os.IsNotExist “stopped working”.
If you care about the recognizable cause, use %w. Otherwise you are left with only a string from the cause, and a string, as we already found out, is a finicky and platform-dependent thing.

Mistake #3: treating not exist as a “fatal” error in all scenarios.
For many applications, the absence of a data file is a normal state on first launch. If you immediately crash with an error, you make the program “fragile”: it cannot start in a clean environment.

Mistake #4: trying to “fix” permission by creating directories and retrying.
Permissions are not a temporary network glitch. If the OS says “no,” usually you need to either change the path, run with different rights, or change the filesystem permissions. Retries here usually just annoy users.

Mistake #5: confusing “file not found” with “invalid path”.
These are different worlds: “not found” may mean you should create the file; “invalid path” usually means a problem with input data or configuration. It is useful to remember: invalid path is not a reason to create directories “just in case,” but a reason to look at what string was passed into your file function.

1
과제
Go SELF, 레벨 39, 레슨 4
잠금
저장소 센서
저장소 센서
1
과제
Go SELF, 레벨 39, 레슨 4
잠금
패스 저장
패스 저장
1
과제
Go SELF, 레벨 39, 레슨 4
잠금
스마트 로더
스마트 로더
1
과제
Go SELF, 레벨 39, 레슨 4
잠금
문제 해설
문제 해설
1
설문조사/퀴즈
파일, 레벨 39, 레슨 4
사용 불가능
파일
파일
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION