Errors & Panic
Error handling in Go
Introduction
In this lesson, you'll learn about errors & panic in Go. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with error handling in go.
Go has its own approach to error handling in go, which we'll explore step by step.
The Go Way
Let's see how Go handles this concept. Here's a typical example:
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("not found")
func getUser(id int) (*User, error) {
u, ok := users[id]
if !ok {
return nil, fmt.Errorf("user %d: %w", id, ErrNotFound)
}
return u, nil
}
u, err := getUser(42)
if err != nil {
if errors.Is(err, ErrNotFound) {
fmt.Println("missing")
} else {
fmt.Println("error:", err)
}
}
// Panic — like unrecoverable JS throw
// Use only for programmer errors, not normal flow
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered:", r)
}
}()
panic("something went very wrong")Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
class NotFoundError extends Error {
constructor(msg) { super(msg); this.name = "NotFoundError"; }
}
function getUser(id) {
if (!users.has(id)) throw new NotFoundError("user " + id);
return users.get(id);
}
try {
const u = getUser(42);
} catch (err) {
if (err instanceof NotFoundError) console.log("missing");
else throw err;
}You may be used to different syntax or behavior.
Go returns error values; JS throws exceptions
You may be used to different syntax or behavior.
Go errors.Is() checks error identity; JS uses instanceof
You may be used to different syntax or behavior.
Go panic/recover for catastrophic failures; JS throw/catch for everything
You may be used to different syntax or behavior.
Go error wrapping with %w allows errors.Is through the chain
Step-by-Step Breakdown
1. Sentinel Errors
Go package-level error variables (var ErrNotFound = errors.New) replace JS custom error classes for identity comparison.
class NotFoundError extends Error {}var ErrNotFound = errors.New("not found")2. errors.Is
errors.Is checks if any error in the chain matches, working through fmt.Errorf %w wrapping.
err instanceof NotFoundErrorerrors.Is(err, ErrNotFound)3. Panic vs Throw
panic is for programmer errors (nil pointer, index out of bounds) — not for expected failures. Use error returns for expected failures.
Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- Go returns error values; JS throws exceptions
- Go errors.Is() checks error identity; JS uses instanceof
- Go panic/recover for catastrophic failures; JS throw/catch for everything
Key Takeaways
- Go returns errors; JS throws exceptions
- Sentinel errors replace custom error classes
- errors.Is works through error chains
- panic for bugs; error returns for expected failures