Golang Tutorial 12: Error handling
Errors as values in Go: wrapping with %w, errors.Is, errors.As and the new errors.AsType, sentinel vs typed errors, errors.Join, when a panic is fine, and a new Go 1.27 vet check for wrapped error pointers. Runnable examples and an exercise.
Go has no exceptions. A function that can fail returns an error as its last value, and the caller checks it. People new to Go complain about all the if err != nil lines. I get it, it's quite a lot of typing. But I've come to like it, because the failure path is right there in the code you're reading instead of hidden in a try block three files away.
In this blog we will look at errors as values, wrapping with %w, errors.Is and errors.As (plus the newer errors.AsType), sentinel and typed errors, errors.Join, when a panic is the right call, and a go vet check added in Go 1.27. Level: beginner. You should be fine with interfaces and pointers from Tutorial 11 and Tutorial 10, since error is just an interface. Everything was run on Go 1.27.3.
mkdir errorsdemo && cd errorsdemo
go mod init example.com/errorsdemo
mkdir basics wrapping typed join panics exercise
Errors are values
error is a built in interface with one method:
type error interface {
Error() string
}
Anything with an Error() string method is an error. The simplest way to make one is errors.New.
package main
import (
"errors"
"fmt"
"os"
"strconv"
)
func parsePort(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, err
}
if n < 1 || n > 65535 {
return 0, errors.New("port out of range")
}
return n, nil
}
func main() {
for _, in := range []string{"8080", "http", "70000"} {
port, err := parsePort(in)
if err != nil {
fmt.Printf("%q: %v\n", in, err)
continue
}
fmt.Printf("%q: port %d\n", in, port)
}
_, err := os.ReadFile("does-not-exist.txt")
fmt.Println(err)
}
"8080": port 8080
"http": strconv.Atoi: parsing "http": invalid syntax
"70000": port out of range
open does-not-exist.txt: no such file or directory
The pattern is always the same. Check the error first, return or handle it, and only then use the other values. When there's an error the other return values are usually zero and you shouldn't trust them.
Error strings start with a lower case letter and have no full stop at the end, because they get glued into longer messages. go vet won't complain about this but linters like staticcheck will.
Wrapping with %w
Returning err as is loses context. "no such file or directory" from deep inside a service doesn't tell you which file or why you were reading it. fmt.Errorf with the %w verb adds a message and keeps the original error inside, so callers can still check for it.
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
// ErrNotFound is a sentinel error: callers compare against it with errors.Is.
var ErrNotFound = errors.New("link not found")
var links = map[string]string{"go": "https://go.dev"}
func lookup(code string) (string, error) {
url, ok := links[code]
if !ok {
return "", fmt.Errorf("lookup %q: %w", code, ErrNotFound)
}
return url, nil
}
func loadConfig(path string) ([]byte, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("load config: %w", err)
}
return b, nil
}
func main() {
_, err := lookup("xyz")
fmt.Println(err)
fmt.Println("== ErrNotFound:", err == ErrNotFound)
fmt.Println("errors.Is:", errors.Is(err, ErrNotFound))
fmt.Println("unwrapped:", errors.Unwrap(err))
_, err = loadConfig("/nope/shorty.yaml")
fmt.Println(err)
fmt.Println("is fs.ErrNotExist:", errors.Is(err, fs.ErrNotExist))
// %v instead of %w keeps the text but drops the chain.
flat := fmt.Errorf("lookup: %v", ErrNotFound)
fmt.Println("flattened, errors.Is:", errors.Is(flat, ErrNotFound))
}
lookup "xyz": link not found
== ErrNotFound: false
errors.Is: true
unwrapped: link not found
load config: open /nope/shorty.yaml: no such file or directory
is fs.ErrNotExist: true
flattened, errors.Is: false
Look at the second and third lines. Once an error is wrapped, == stops working. errors.Is walks the chain of wrapped errors and finds ErrNotFound inside. That's why you should use errors.Is even when you think nothing wraps the error today. Somebody will add a wrap next month.
The last line shows %v gives the same text but cuts the chain. Sometimes that's what you want, for example at a package boundary where you don't want callers to depend on an internal error. Most of the time it's actually a typo for %w.
A small thing happened while I was writing this post itself. My first version of that last Println had the label "with %v, errors.Is:", and go vet flagged it: fmt.Println call has possible Printf formatting directive %v. Vet was right, it looked like a format string passed to Println. I renamed the label. Run go vet ./... all the time, it's cheap.
Sentinel errors and typed errors
ErrNotFound above is a sentinel error: a package level variable that callers compare against. Use one when the caller only needs to know which failure happened. The standard library is full of them: io.EOF, sql.ErrNoRows, fs.ErrNotExist.
When the caller needs data about the failure, use a typed error, a struct that implements error. Then get it back out with errors.As.
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
// ValidationError carries data the caller can act on.
type ValidationError struct {
Field string
Reason string
}
func (e *ValidationError) Error() string {
return e.Field + ": " + e.Reason
}
func createLink(code, url string) error {
if len(code) < 3 {
return &ValidationError{Field: "code", Reason: "must be at least 3 characters"}
}
if url == "" {
return &ValidationError{Field: "url", Reason: "is required"}
}
return nil
}
func handler(code, url string) error {
if err := createLink(code, url); err != nil {
return fmt.Errorf("create link: %w", err)
}
return nil
}
func main() {
err := handler("ab", "https://example.com")
fmt.Println(err)
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Printf("400 bad request, field=%s reason=%s\n", ve.Field, ve.Reason)
}
// Go 1.26+: errors.AsType, no target variable needed.
if ve, ok := errors.AsType[*ValidationError](handler("abc", "")); ok {
fmt.Println("field from AsType:", ve.Field)
}
_, err = os.Open("/nope")
if pe, ok := errors.AsType[*fs.PathError](err); ok {
fmt.Println("op:", pe.Op, "path:", pe.Path, "err:", pe.Err)
}
}
create link: code: must be at least 3 characters
400 bad request, field=code reason=must be at least 3 characters
field from AsType: url
op: open path: /nope err: no such file or directory
errors.As needs a pointer to a variable of the target type, so for a *ValidationError you pass a **ValidationError. That double pointer confuse everyone the first time. errors.AsType, added in Go 1.26, is the generic version and reads much better: the type goes in the brackets, and you get the value and an ok flag back. I use only AsType in new code now. Older code and most blog posts still use As, so you need to read both.
ValidationError uses a pointer receiver for Error(), which means *ValidationError is the error type and that's what you return and look for. Mixing up ValidationError and *ValidationError here is a classic way to get an As that never matches.
In a web handler this is where typed errors pay off. The handler checks for *ValidationError and returns 400, checks errors.Is(err, ErrNotFound) and returns 404, and everything else becomes a 500. The handlers in the standard library REST API post are a good place to try this. And once 4xx and 5xx are cleanly split, you can alert only on the real failures, which is what sending Slack alerts only for errors that became 5xx responses is about.
The Go 1.27 vet check for %w
Go 1.27 added a check to the vet printf analyzer that is about this exact pointer confusion. Here is a value receiver error being wrapped as a pointer:
package main
import (
"errors"
"fmt"
)
type QuotaError struct{ Limit int }
func (e QuotaError) Error() string { return fmt.Sprintf("quota of %d exceeded", e.Limit) }
func main() {
qe := &QuotaError{Limit: 100}
err := fmt.Errorf("create link: %w", qe)
fmt.Println(err)
var target QuotaError
fmt.Println("errors.As value:", errors.As(err, &target))
}
create link: quota of 100 exceeded
errors.As value: false
It compiles and prints a normal message, but errors.As with a QuotaError target doesn't match, because the chain holds a *QuotaError. go vet on 1.27.3 catches it:
main.go:14:34: %w wants operand of error type QuotaError, not pointer type *QuotaError (defeats errors.Is)
go test runs a subset of vet checks before the tests, and printf is one of them. I added an empty test file next to this program and go test refused to build it with the same message. So you'll often see this one without asking. Fix it by wrapping *qe (the value) or by switching the type to pointer receivers everywhere.
errors.Join for many errors
Validation usually finds more than one problem, and returning only the first one makes users fix things one at a time. errors.Join (Go 1.20) combines errors into one.
package main
import (
"errors"
"fmt"
"net/url"
"strings"
)
var ErrEmpty = errors.New("empty value")
type Link struct {
Code string
URL string
}
func validate(l Link) error {
var errs []error
if l.Code == "" {
errs = append(errs, fmt.Errorf("code: %w", ErrEmpty))
} else if strings.ContainsAny(l.Code, " /") {
errs = append(errs, errors.New("code: no spaces or slashes"))
}
if l.URL == "" {
errs = append(errs, fmt.Errorf("url: %w", ErrEmpty))
} else if u, err := url.Parse(l.URL); err != nil || u.Scheme == "" {
errs = append(errs, errors.New("url: needs a scheme like https://"))
}
return errors.Join(errs...) // nil when errs is empty
}
func main() {
fmt.Println(validate(Link{Code: "go", URL: "https://go.dev"}))
err := validate(Link{Code: "a b", URL: ""})
fmt.Println(err)
fmt.Println("has empty:", errors.Is(err, ErrEmpty))
// %w more than once also builds a multi-error.
both := fmt.Errorf("save failed: %w; cleanup failed: %w", ErrEmpty, errors.New("disk full"))
fmt.Println(both, errors.Is(both, ErrEmpty))
}
<nil>
code: no spaces or slashes
url: empty value
has empty: true
save failed: empty value; cleanup failed: disk full true
Two nice details. errors.Join returns nil when every error is nil or the list is empty, so you can return it directly with no if len(errs) > 0. And errors.Is searches all the joined errors, which is how has empty came out true even though ErrEmpty was the second one.
The joined message uses a newline between errors. That's fine on a terminal. In a JSON response or a single line log I usually return the list of messages instead.
When is panic OK?
Rarely. Panic is for bugs and for "this program cannot start". Bad input or a missing row is a normal failure and gets a normal error. Two places where I'm fine with it:
- Start-up with constant input, like
regexp.MustCompilewith a pattern in the source code. If that pattern is wrong it's a bug, and you want to find out the moment the program starts. - A recover at the top of a request, so one bad request doesn't kill the whole server.
package main
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"regexp"
)
// MustCompile panics, which is fine at start-up with a constant pattern.
var codeRe = regexp.MustCompile(`^[a-zA-Z0-9]{3,16}$`)
func recoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
log.Printf("panic in %s %s: %v", r.Method, r.URL.Path, v)
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
func main() {
fmt.Println(codeRe.MatchString("abc123"), codeRe.MatchString("a"))
mux := http.NewServeMux()
mux.HandleFunc("GET /links/{code}", func(w http.ResponseWriter, r *http.Request) {
var m map[string]string
m[r.PathValue("code")] = "oops" // assignment to entry in nil map
})
rec := httptest.NewRecorder()
recoverer(mux).ServeHTTP(rec, httptest.NewRequest("GET", "/links/abc", nil))
fmt.Println("status:", rec.Code, "body:", rec.Body.String())
}
true false
2026/11/19 12:06:57 panic in GET /links/abc: assignment to entry in nil map
status: 500 body: internal error
The handler writes to a nil map, which panics. The middleware's deferred recover catches it, logs it and sends a 500. Note that net/http already recovers panics per connection and logs them, but it just drops the connection, so the client gets no response at all. Your own middleware lets you return a proper 500 and log it the way the rest of your logs look.
recover only works inside a deferred function, and only in the same goroutine that panicked. A panic in a goroutine you started from the handler still takes down the whole process. See, this trips people up. Recovery middleware feels like a safety net for everything, and it isn't.
A few habits
- Handle an error once. Either log it or return it. Logging and returning means the same failure shows up three times in your logs as it goes up the stack.
- Add context that the caller doesn't have: the code, the path, the ID. Don't repeat the function's own name at every level, the messages get very long.
- Don't ignore errors with
_unless you can say why.defer f.Close()on a file you only read is fine. On a file you wrote, check the error fromClose, that's when buffered data gets flushed.
Exercise
Write sumLines(input string) (int, error) that adds up one integer per line. Bad lines should not stop the sum. Collect an error for each one with its line number, and return them all together. Callers must be able to check errors.Is(err, ErrEmptyLine) for blank lines and get the first bad line number with errors.AsType.
Hint: a typed error with an Unwrap() error method keeps the chain working.
package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
var ErrEmptyLine = errors.New("empty line")
type LineError struct {
Line int
Err error
}
func (e *LineError) Error() string { return "line " + strconv.Itoa(e.Line) + ": " + e.Err.Error() }
func (e *LineError) Unwrap() error { return e.Err }
// sumLines adds one integer per line and reports every bad line.
func sumLines(input string) (int, error) {
var total int
var errs []error
for i, line := range strings.Split(input, "\n") {
line = strings.TrimSpace(line)
if line == "" {
errs = append(errs, &LineError{Line: i + 1, Err: ErrEmptyLine})
continue
}
n, err := strconv.Atoi(line)
if err != nil {
errs = append(errs, &LineError{Line: i + 1, Err: err})
continue
}
total += n
}
return total, errors.Join(errs...)
}
func main() {
total, err := sumLines("10\n20\nabc\n\n5")
fmt.Println("total:", total)
fmt.Println(err)
fmt.Println("any empty line?", errors.Is(err, ErrEmptyLine))
if le, ok := errors.AsType[*LineError](err); ok {
fmt.Println("first bad line:", le.Line)
}
}
total: 35
line 3: strconv.Atoi: parsing "abc": invalid syntax
line 4: empty line
any empty line? true
first bad line: 3
Notice it returns a partial total and an error at the same time. That's allowed in Go, just document it, because most callers assume the value is useless when err != nil. Next in the series is packages and modules, where these error types start living in their own packages.