Error Handling in Go
Learn how errors work in Go: errors as values, checking errors, creating errors, custom error types, defer for cleanup, and panic/recover.
Introduction to Errors
In Go, errors are values. Functions that can fail return an `error` as the last return value. There is no try/catch; you check `if err != nil` and handle the error.
1. What is an Error?
Errors are values returned from functions.
Checking Errors
Always check the error return value. Use `if err != nil` and then return, log, or handle. Ignoring errors leads to bugs.
1. Basic Error Check
if err != nil { ... }
2. Using the Error Value
err.Error() and type assertions.
Creating Errors
Use `errors.New("message")` for a simple error, or `fmt.Errorf("format", args...)` to build a message. Wrap existing errors with `%w` for error chains.
1. errors.New
Create a simple error.
2. fmt.Errorf and Wrapping
Format an error message; use %w to wrap.
Custom Error Types
Implement the `error` interface (method `Error() string`) on a struct to create custom errors. Use type assertions to detect your type.
1. Struct Implementing error
Add an Error() string method.
defer for Cleanup
`defer` runs a function call when the surrounding function returns, whether it returns normally or due to an error. Use it for closing files, unlocking mutexes, etc.
1. defer Execution
Deferred calls run in LIFO order.
panic and recover
`panic` stops normal execution and runs defers. `recover` (only useful inside a deferred function) can capture the panic value. Use for truly unrecoverable situations; prefer returning `error` for normal flow.
1. panic
Stop execution and run defers.
2. recover
Capture panic in a deferred function.