{"record":{"id":"1d54f98361ad7485","repo":"unknwon/the-way-to-go_ZH_CN","slug":"math-square-root-of-negative-number","errorCode":null,"errorMessage":"math - square root of negative number","messagePattern":"math - square root of negative number","errorType":"error_code","errorClass":null,"httpStatus":null,"severity":"info","filePath":"eBook/13.1.md","lineNumber":18,"sourceCode":"# 13.1 错误处理\n\nGo 有一个预先定义的 error 接口类型\n\n```go\ntype error interface {\n\tError() string\n}\n```\n\n错误值用来表示异常状态；我们可以在 [5.2 节](05.2.md)中看到它的标准用法。处理文件操作的例子可以在 [12 章](12.0.md)找到；我们将在 [15 章](15.0.md)看到网络操作的例子。`errors` 包中有一个 `errorString` 结构体实现了 `error` 接口。当程序处于错误状态时可以用 `os.Exit(1)` 来中止运行。\n\n## 13.1.1 定义错误\n\n任何时候当你需要一个新的错误类型，都可以用 `errors` 包（必须先 `import`）的 `errors.New()` 函数接收合适的错误信息来创建，像下面这样：\n\n```go\nerr := errors.New(\"math - square root of negative number\")\n```\n\n在示例 13.1 中你可以看到一个简单的用例：\n\n示例 13.1 [errors.go](examples/chapter_13/errors.go)：\n\n```go\n// errors.go\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar errNotFound error = errors.New(\"Not found error\")\n\nfunc main() {","sourceCodeStart":1,"sourceCodeEnd":36,"githubUrl":"https://github.com/unknwon/the-way-to-go_ZH_CN/blob/7a54d34d3657084b6a59e5618bd069b912d571aa/eBook/13.1.md#L1-L36","documentation":"This is documentation text, not shipped library code: section 13.1 of the Go eBook introduces error values with err := errors.New(\"math - square root of negative number\"). The message is the book's canonical example of a descriptive error string for an invalid-domain condition; errors.New allocates an errorString carrying exactly that text.","triggerScenarios":"Nothing in the repo produces it at runtime — the string only exists in a Markdown code fence. You hit it by copying the snippet into your own Sqrt-like function and calling it with a negative argument, or by grepping for error idioms and landing here.","commonSituations":"Readers pasting book snippets into real code and later finding this exact text in logs; tests asserting on the exact message string; project renames where the 'math -' prefix no longer matches the actual package name; noticing the snippet as printed does not compile standalone (err is declared and not used).","solutions":["Treat the snippet as a template: keep the shape, rewrite the text for your domain, e.g. errors.New(\"geometry: square root of negative number\")","If you pasted the one-liner verbatim, fix the compile error by using err (return it, log it) or discarding with _ = err while experimenting","If you already shipped this exact text and match on it, replace string comparison with a package-level sentinel: var ErrNegativeSqrt = errors.New(...) plus errors.Is","Run go vet / staticcheck after pasting snippets to catch unused imports (errors) and unused variables"],"exampleFix":"// before (copied verbatim; also fails to compile: err declared and not used)\nerr := errors.New(\"math - square root of negative number\")\n\n// after (package-level sentinel, prefix matches your package, comparable)\nvar ErrNegativeSqrt = errors.New(\"geometry: square root of negative number\")\n\nfunc Sqrt(f float64) (float64, error) {\n\tif f < 0 {\n\t\treturn 0, fmt.Errorf(\"Sqrt(%g): %w\", f, ErrNegativeSqrt)\n\t}\n\treturn math.Sqrt(f), nil\n}","handlingStrategy":"validation","validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":["Treat book snippets as templates: rewrite the message and prefix for your package before shipping","If you copy a sentinel string, define it once as an exported package-level var so callers use errors.Is, not text matching","The one-liner as printed does not compile standalone (err declared and not used) — use it in a return or discard it with _ = err","Run go vet after pasting snippets to catch unused imports and variables"],"tags":["go","documentation","errors-new","example-code"],"backgroundTag":null,"analyzedSha":"7a54d34d3657084b6a59e5618bd069b912d571aa","analyzedAt":"2026-08-15T15:13:06.026Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}