unknwon/the-way-to-go_ZH_CN · error

"ERROR occurred: " + err.Error()

Error message

"ERROR occurred: " + err.Error()

What it means

Section 18.10 presents two termination styles for unrecoverable errors: print-and-os.Exit(1), or panic("ERROR occurred: " + err.Error()). The panic variant crashes with a full stack trace — that is the point: maximum debugging information at the cost of a hard, unclean abort.

Source

Thrown at eBook/18.10.md:16

# 18.10 其他

如何在程序出错时终止程序:

```go	
if err != nil {
   fmt.Printf("Program stopping with error %v", err)
   os.Exit(1)
}
```

或者:

```go
if err != nil { 
	panic("ERROR occurred: " + err.Error())
}
```

## 链接

- [目录](directory.md)
- 上一节:[网络和网页应用](18.9.md)
- 下一节:[出于性能考虑的最佳实践和建议](18.11.md)

View on GitHub (pinned to 7a54d34d36)

Solutions

  1. Prefer returning/propagating the error and deciding at top level how to exit
  2. Use log.Fatalf("ERROR occurred: %v", err) when a clean exit with a log line is acceptable
  3. Keep the panic only when you specifically want the goroutine dump for diagnosis
  4. Wrap third-party call sites in deferred recover when interop code panics this way

Example fix

// before
if err != nil {
    panic("ERROR occurred: " + err.Error())
}

// after
if err != nil {
    log.Fatalf("ERROR occurred: %v", err) // clean exit, still loud
}
Defensive patterns

Strategy: try-catch

Try / catch

// keep the abort contained and observable
defer func() {
    if r := recover(); r != nil {
        log.Printf("recovered from fatal branch: %v", r)
        os.Exit(1)
    }
}()
if err != nil {
    panic("ERROR occurred: " + err.Error())
}

Prevention

When it happens

Trigger: Any err != nil reaching this branch at a point where the program decides continuation is impossible; the section frames it as the alternative to os.Exit for must-stop situations.

Common situations: Final-mile error handling in main after retries are exhausted; porting shell scripts whose set -e / exit-on-error semantics are being mimicked; cleanup code accidentally skipped because panic bypasses it.

Related errors


AI-assisted analysis of unknwon/the-way-to-go_ZH_CN@7a54d34d36 (2026-08-15). Data as JSON: /api/errors/ff3f50ed257edf46. Report an issue: GitHub.