Prove your Go code works: table-driven tests & subtests, helpers like t.Cleanup, t.Parallel and TestMain, mocks & fakes via interfaces, benchmarks with pprof, plus fuzzing and the race detector.
In Go, an error is a value like any other. This sounds simple, but it's revolutionary: there are no exceptions that delegate control to a higher hierarchy level. Instead, Go forces us to explicitly handle every error. The error interface forms the foundation — it defines a single method: Error() string.
This simplicity enables immense flexibility. We can create custom error types that implement the interface or extend existing errors. The key insight: any type with an Error() string method is an error. This makes the interface one of Go's most elegant designs.
The error interface as a Contract
The error interface is Go's mechanism for treating errors as first-class citizens. It is an interface with a single method Error() string, meaning any type with this method can be used as an error. This enables the creation of rich, typed errors that seamlessly integrate with standard error handling.
Here's the basic structure of how Go handles errors — explicit and predictable:
package main
import (
"fmt"
"errors"
)
var ErrNotFound = errors.New("resource not found")
func findUser(id int) (string, error) {
if id == 0 {
return "", ErrNotFound
}
return fmt.Sprintf("User%d", id), nil
}
func main() {
user, err := findUser(0)
if err != nil {
fmt.Println("Error:", err)
// → Error: resource not found
return
}
fmt.Println("Found:", user)
}
A pattern found throughout the Go standard library is Sentinel Errors — predefined errors exported as package-level variables. These serve as sentinels that mark specific, expected error states. The main advantage: calling code can explicitly check for these known errors.
Sentinel errors are not intended for dynamic errors. They should only be used for conditions that the caller wants to explicitly check and handle differently.
package main
import (
"errors"
"fmt"
)
var ErrInvalidInput = errors.New("invalid input")
func parse(input string) (int, error) {
if input == "" {
return 0, ErrInvalidInput
}
return 42, nil
}
func process(input string) error {
num, err := parse(input)
if err != nil {
if errors.Is(err, ErrInvalidInput) {
fmt.Println("Please provide valid input")
// → Please provide valid input
return nil
}
return err
}
fmt.Println("Result:", num)
return nil
}
func main() {
process("")
}
⚠ Common mistake: Developers tend to use
errors.Newinside functions to create dynamic error messages. This creates new error instances on each call —errors.Is(err, ErrSomething)will fail even if the message is identical. Sentinel errors must be defined as package-level variables for identity checks to work.
Check: Why should sentinel errors be defined as package-level variables rather than local variables inside functions?
Answer: So that errors.Is() works correctly, as it checks the identity of the error instance
errors.Is() does not just check the error message, it also checks the identity of the error instance through unwrapping. If ErrInvalidInput is created anew on each call, they are different instances and Is() will fail. Package-level variables ensure the same instance is always used.
Takeaways:
error interface with its single method Error() string is the foundation of Go's error handling.errors.New or fmt.Errorf for simple errors, but define sentinel errors at the package level for errors that callers need to explicitly check.Before Go 1.13, there was a major problem: when a function returned an error from a deeper function, the context was lost. You could propagate the error, but you couldn't recognize what the original error was. Go 1.13 introduced the %w verb to fmt.Errorf, which allows you to wrap errors while preserving the original error.
Wrapping is essential for recreating stack traces and keeping original errors identifiable in deep call chains. Instead of fmt.Errorf("that did not work: %v", err), we now write fmt.Errorf("that did not work: %w", err).
Error Wrapping vs. Error Replacement
Wrapping means embedding an existing error into a new error with additional context. The original error is preserved as the cause and can be extracted using errors.Is() and errors.As(). Replacement (e.g., with %v or %s) breaks this chain and makes the original error invisible to standard introspection.
Here's how wrapping works in practice:
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
func readFile(name string) (string, error) {
if name == "missing.txt" {
return "", ErrNotFound
}
return "contents", nil
}
func processFile(name string) (string, error) {
content, err := readFile(name)
if err != nil {
return "", fmt.Errorf("error processing %s: %w", name, err)
}
return content, nil
}
func main() {
_, err := processFile("missing.txt")
if err != nil {
fmt.Println("Wrapped Error:", err)
// → Wrapped Error: error processing missing.txt: not found
}
}
With wrapping alone, we cannot find the original error. errors.Is(err, target error) bool searches through the error chain for the given error (by identity or via unwrapping). errors.As(err, target interface{}) bool does the same but for types — perfect for custom error types.
These two functions are the key to implementing idiomatic error retrieval in Go.
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
func findFile(name string) (string, error) {
if name == "" {
return "", ErrNotFound
}
return "found", nil
}
func openFile(name string) (string, error) {
content, err := findFile(name)
if err != nil {
return "", fmt.Errorf("cannot open file: %w", err)
}
return content, nil
}
func readFile(name string) (string, error) {
content, err := openFile(name)
if err != nil {
return "", fmt.Errorf("cannot read file %s: %w", name, err)
}
return content, nil
}
func main() {
_, err := readFile("")
if err != nil {
if errors.Is(err, ErrNotFound) {
fmt.Println("Original error recognized: not found")
// → Original error recognized: not found
}
fmt.Println("Full Error:", err)
// → Full Error: cannot read file : cannot open file: not found
}
}
⚠ Common mistake: Developers use
errors.Is()with a newly created error —errors.New("not found")will cause the check to fail because it is a different instance. The second parameter must be the exact package variable or a wrapped error that contains it.
Check: What is the main difference between fmt.Errorf with %v and %w?
Answer: %w preserves the original error for errors.Is/As, %v replaces it with its string representation
The crucial difference is that %w stores the original error as the cause, so it can later be found via errors.Unwrap(), errors.Is() or errors.As(). %v and %s only convert the error to a string and break the chain.
Takeaways:
%w in fmt.Errorf to wrap errors and preserve the original error.errors.Is(err, target) searches through the entire error chain for a specific error (identity check).errors.As(err, target) searches for a specific error type in the chain — perfect for custom error types.A simple errors.New or fmt.Errorf only provides a string. But what if we need additional information? An HTTP handler might want to know the status code. A database error might include the affected table name. This is where Custom Error Types come into play.
By creating a custom type that implements the error interface, we can add any additional fields while maintaining compatibility with standard error handling.
Custom Error Types as Domain-Specific Errors
A custom error type is a struct that implements the error interface along with additional methods and fields. This enables typed errors that go beyond mere text messages and can carry domain-specific information.
Here is a classic example of a structured error:
package main
import "fmt"
type DomainError struct {
Code int
Message string
Detail string
}
func (e *DomainError) Error() string {
return fmt.Sprintf("%s (Code: %d) — %s", e.Message, e.Code, e.Detail)
}
func validateInput(input string) error {
if input == "" {
return &DomainError{
Code: 400,
Message: "validation error",
Detail: "input cannot be empty",
}
}
return nil
}
func main() {
err := validateInput("")
if err != nil {
fmt.Println("Error:", err)
// → Error: validation error (Code: 400) — input cannot be empty
}
}
The true benefit of custom error types is revealed in combination with errors.As(). This function allows us to cast an error to a specific type — similar to type assertions for interfaces. This is especially useful when we want to access specific fields or methods of the error type.
In Go 1.13+, we can also implement the Unwrap() error method to support chaining for wrapping. Without this method, errors.Is() and errors.As() will not work through the wrapped chain.
package main
import (
"errors"
"fmt"
)
type DatabaseError struct {
Table string
Err error
}
func (e *DatabaseError) Error() string {
return fmt.Sprintf("database error on table %s: %v", e.Table, e.Err)
}
func (e *DatabaseError) Unwrap() error {
return e.Err
}
func query(table string) error {
baseErr := errors.New("connection failed")
return &DatabaseError{Table: table, Err: baseErr}
}
func getUsers() error {
err := query("users")
if err != nil {
return fmt.Errorf("failed to retrieve users: %w", err)
}
return nil
}
func main() {
err := getUsers()
if err != nil {
var dbErr *DatabaseError
if errors.As(err, &dbErr) {
fmt.Printf("Error on table: %s\n", dbErr.Table)
// → Error on table: users
}
}
}
⚠ Common mistake: Simply implementing the
errorinterface is not sufficient forerrors.Is()orerrors.As()to work through wrapping. Without theUnwrap() errormethod, the error chain cannot be traversed. Every custom error type that will be wrapped should implement this method if it embeds other errors.
Check: Which method must a custom error type implement in addition to Error() for errors.As() to work correctly when the error has been wrapped?
Answer: Unwrap() error
The Unwrap() method must be implemented so that the standard library functions errors.Is() and errors.As() can traverse the error chain. Without Unwrap(), the custom error type is a leaf in the chain and hides all wrapped errors.
Takeaways:
error interface and contain additional domain-specific fields.Unwrap() error method to enable integration with errors.Is() and errors.As().errors.As() allows type-safe casting of errors, similar to a type assertion.Go's philosophy is clear: errors are values, and normal errors should be returned as error. Panic is the mechanism for catastrophic errors from which the program cannot recover — or for programming errors that should never occur in production. A panic breaks normal execution and begins stack unwinding.
Important: panic is not for expected errors! A failed network request? A missing file? These are all cases for error. A nil pointer dereference or an unreachable code path? These might be signs of a panic.
panic vs error: The Decision Rule
Use panic when the program is in an invalid state from which it cannot recover. Use error when an expected error condition occurs that needs to be handled by the caller. The rule: "Don't panic" — except in extraordinary circumstances.
Here's how panic works and when it's appropriate:
package main
import "fmt"
func divide(a, b int) int {
if b == 0 {
panic("division by zero not allowed")
}
return a / b
}
func safeDivide(a, b int) (result int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic intercepted: %v", r)
}
}()
return divide(a, b), nil
}
func main() {
result, err := safeDivide(10, 0)
if err != nil {
fmt.Println("Handled error:", err)
// → Handled error: panic intercepted: division by zero not allowed
}
}
A panic propagates up through the call stacks until it reaches either the main goroutine (causing the program to crash) or is caught by a recover. recover is a builtin function that can only be called inside deferred functions.
The classic pattern is defer/recover at the beginning of goroutines or in main functions, to catch panics and convert them to errors. This is especially important in servers, where a single panic should not crash the entire program.
package main
import (
"fmt"
"log"
)
func processWithRecovery(task string) {
defer func() {
if r := recover(); r != nil {
log.Printf("Panic in %s recovered: %v", task, r)
// → Panic in failed recovered: something went wrong
}
}()
if task == "failed" {
panic("something went wrong")
}
fmt.Println("Task", task, "succeeded")
}
func main() {
processWithRecovery("succeeded")
processWithRecovery("failed")
fmt.Println("Program continues")
// → Task succeeded succeeded
// → Panic in failed recovered: something went wrong
// → Program continues
}
⚠ Common mistake: Developers try to call
recover()outside a deferred function. This is a compile error.recoveronly works insidedeferand catches only panics that occur after the defer's function execution begins — not those that occur in the same function before the defer.
Check: When is the use of panic appropriate?
Answer: When an unexpected nil value occurs, indicating a programming error
Panic is reserved for extraordinary circumstances where the program is in an inconsistent state. Expected error conditions should always be returned as error. A nil pointer that should never be nil or an impossible code path are typical panic cases.
Takeaways:
panic is for catastrophic, unexpected errors — not for normal error handling.recover catches panics, but only works inside deferred functions.defer/recover pattern should be used at the beginning of goroutines to keep the entire program stable.When building an HTTP API, we need to map Go errors to HTTP status codes. The challenge: a Go error can mean different HTTP status codes depending on context. An ErrNotFound might be 404 (Not Found), but it could also be 400 (Bad Request) if the input was invalid.
A best practice is to create an error handler that translates domain errors into HTTP responses. It is important not to expose too many details to the client (security!) while still logging enough information for debugging.
Error to HTTP-Status Mapping as Translation Layer
Mapping domain errors to HTTP status codes is a translation task. We need to consider: security (do not reveal internal details), consistency (same errors = same codes), and user-friendliness (clear, actionable error messages).
Here's what clean HTTP error handling looks like:
package main
import (
"errors"
"fmt"
"net/http"
)
var (
ErrNotFound = errors.New("resource not found")
ErrInvalidInput = errors.New("invalid input")
ErrInternal = errors.New("internal error")
)
func handleError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, ErrNotFound):
http.Error(w, "Resource not found", http.StatusNotFound)
case errors.Is(err, ErrInvalidInput):
http.Error(w, "Invalid request", http.StatusBadRequest)
case errors.Is(err, ErrInternal):
fmt.Println("Internal error:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
default:
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
func getResourceHandler(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("id")
if id == "" {
handleError(w, ErrInvalidInput)
return
}
resource, err := findResource(id)
if err != nil {
handleError(w, err)
return
}
fmt.Fprintf(w, "Resource: %s", resource)
}
func findResource(id string) (string, error) {
if id == "missing" {
return "", ErrNotFound
}
return "Resource-" + id, nil
}
func main() {
http.HandleFunc("/resource", getResourceHandler)
fmt.Println("Server starting on :8080")
// → Server starting on :8080
http.ListenAndServe(":8080", nil)
}
A common misconception: put everything in errors. But errors and logs serve different purposes. Errors are for code — they are handled programmatically. Logs are for humans — they help with debugging and monitoring.
The golden rule: log errors with enough context so a developer can reproduce the problem. But do not expose too many details to the end user (security risk).
package main
import (
"errors"
"fmt"
"log"
"os"
)
var ErrOpenFile = errors.New("failed to open file")
func processFile(name string) error {
f, err := os.Open(name)
if err != nil {
log.Printf("Error opening %s: %v", name, err)
// → Error opening nonexistent.txt: open nonexistent.txt: no such file or directory
return fmt.Errorf("processing failed: %w", ErrOpenFile)
}
defer f.Close()
return nil
}
func main() {
err := processFile("nonexistent.txt")
if err != nil {
log.Println("Total error:", err)
// → Total error: processing failed: failed to open file
}
}
⚠ Common mistake: Developers tend to include sensitive information (database connection strings, passwords, internal paths) in error messages or logs that get returned to the client. This is a serious security risk. Logs should only be stored server-side and errors returned to clients should be neutral and safe.
Check: What is the main difference between errors and logs regarding the end user?
Answer: Errors are for programmatic processing, logs are for humans and should not be passed to end users
Errors are values that are handled in code and can (in safe, neutral forms) be passed to end users. Logs, however, are detective information for developers and should never be directly exposed to end users — especially not with sensitive details.
Takeaways:
Course navigation: ← Module 7 · All 20 modules · Module 9 →