Cursor rules for Go errors with contextual %w wrapping, sentinel versus typed errors, errors.Is/As/AsType checks, log-once handling and error-path tests.
.cursor/rules/go-error-handling-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for Go errors with contextual %w wrapping, sentinel versus typed errors, errors.Is/As/AsType checks, log-once handling and error-path tests."
globs: "**/*"
alwaysApply: false
---
# Go Error Handling Patterns
Applies to: Go code that creates, wraps, inspects, logs or returns errors.
Version baseline: checked against Go 1.27 (`errors.Join` since 1.20, `errors.AsType` since 1.26). Read `go.mod` and use only features available at its `go` directive. Snippets omit import blocks.
## Core principles
- Errors are values: return them as the last result and check them immediately with `if err != nil`.
- Never discard an error silently. If ignoring one is correct, assign it to `_` and say why in a comment.
- Use errors for expected failures (not found, invalid input, timeouts). Reserve `panic` for programmer errors and impossible states; do not use it for control flow across package boundaries.
## Add context while propagating
Return the error up to the layer that can decide what to do, adding what this layer was doing. Use `%w` so callers can still inspect the cause.
```go
func (s *Service) Rename(ctx context.Context, id, name string) error {
u, err := s.repo.Get(ctx, id)
if err != nil {
return fmt.Errorf("rename user %s: %w", id, err)
}
u.Name = name
if err := s.repo.Save(ctx, u); err != nil {
return fmt.Errorf("rename user %s: save: %w", id, err)
}
return nil
}
```
- Messages are lowercase, without trailing punctuation, and describe the operation, not "error occurred" or "failed to".
- Use `%v` instead of `%w` when you deliberately hide the underlying error from callers (for example, at an API boundary where it is an implementation detail).
## Sentinel errors vs error types
- Sentinel value when callers only need to know which condition happened:
`var ErrNotFound = errors.New("user: not found")`, checked with `errors.Is(err, ErrNotFound)`.
- Custom type when callers need data about the failure:
```go
type ValidationError struct {
Field string
Reason string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("invalid %s: %s", e.Field, e.Reason)
}
// Callers, Go 1.26+:
if ve, ok := errors.AsType[*ValidationError](err); ok {
respondBadRequest(w, ve.Field, ve.Reason)
}
// Before Go 1.26:
var ve *ValidationError
if errors.As(err, &ve) {
respondBadRequest(w, ve.Field, ve.Reason)
}
```
- Compare with `errors.Is`/`errors.As`, never with `==` on wrapped errors or by matching `err.Error()` strings.
- Export only the sentinels and types that callers are expected to handle; every exported one is part of your API.
- Combine independent failures (for example, closing several resources) with `errors.Join`.
## Log or return, not both
Handle each error once. Lower layers wrap and return; the top of the request or job (handler, `main`, worker loop) logs it once with structured context and decides the response.
```go
func (h *Handler) rename(w http.ResponseWriter, r *http.Request) {
err := h.svc.Rename(r.Context(), r.PathValue("id"), r.FormValue("name"))
switch {
case err == nil:
w.WriteHeader(http.StatusNoContent)
case errors.Is(err, ErrNotFound):
http.Error(w, "user not found", http.StatusNotFound)
default:
h.log.ErrorContext(r.Context(), "rename user", "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
}
}
```
The standard `log` package has no `Errorf`; use `log/slog` (`logger.Error(msg, "err", err)`) or the project's logger.
## Deferred cleanup
Do not drop errors from `Close` on files you wrote; they can report a failed flush.
```go
func writeReport(path string, data []byte) (err error) {
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("create report: %w", err)
}
defer func() { err = errors.Join(err, f.Close()) }()
_, err = f.Write(data)
return err
}
```
## Test error paths
Use table-driven tests that assert on error identity, not message text:
```go
tests := []struct {
name string
id string
wantErr error
}{
{"missing user", "nope", ErrNotFound},
{"ok", "u1", nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := svc.Rename(ctx, tt.id, "new")
if !errors.Is(err, tt.wantErr) {
t.Fatalf("Rename() error = %v, want %v", err, tt.wantErr)
}
})
}
```
## Verify before finishing
Run these when they are available in the project:
- `gofmt -l .` (no output) and `go vet ./...`
- `go test ./...`
- `errcheck ./...`, or `golangci-lint run` with `errcheck`, `errorlint` and `wrapcheck` if configured
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Go 1.27 service has this rule attached while a developer asks Cursor to add validation errors to a rename operation and handle them in the HTTP layer.
Rename should fail with a validation error that names the field when the new name is empty, and the handler should return 400 for that, 404 for unknown users, and 500 otherwise.
Illustrative; not a recorded model run. A *ValidationError type with Field and Reason, returned unwrapped or wrapped with %w; the service wrapping repository errors with the operation and ID; the handler using errors.AsType[*ValidationError] (or errors.As before Go 1.26) for 400 and errors.Is(err, ErrNotFound) for 404, logging only the unexpected case once with slog; table-driven tests asserting errors.Is/As rather than message strings.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/go-error-handling-patterns.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Go Error Handling Patterns: Wrapping, Sentinels, Types and errors.AsType project conventions"
globs: "**/*"
alwaysApply: false
---
# Go Error Handling Patterns
Applies to: Go code that creates, wraps, inspects, logs or returns errors.
Version baseline: checked against Go 1.27 (`errors.Join` since 1.20, `errors.AsType` since 1.26). Read `go.mod` and use only features available at its `go` directive. Snippets omit import blocks.
## Core principles
- Errors are values: return them as the last result and check them immediately with `if err != nil`.
- Never discard an error silently. If ignoring one is correct, assign it to `_` and say why in a comment.
- Use errors for expected failures (not found, invalid input, timeouts). Reserve `panic` for programmer errors and impossible states; do not use it for control flow across package boundaries.
## Add context while propagating
Return the error up to the layer that can decide what to do, adding what this layer was doing. Use `%w` so callers can still inspect the cause.
```go
func (s *Service) Rename(ctx context.Context, id, name string) error {
u, err := s.repo.Get(ctx, id)
if err != nil {
return fmt.Errorf("rename user %s: %w", id, err)
}
u.Name = name
if err := s.repo.Save(ctx, u); err != nil {
return fmt.Errorf("rename user %s: save: %w", id, err)
}
return nil
}
```
- Messages are lowercase, without trailing punctuation, and describe the operation, not "error occurred" or "failed to".
- Use `%v` instead of `%w` when you deliberately hide the underlying error from callers (for example, at an API boundary where it is an implementation detail).
## Sentinel errors vs error types
- Sentinel value when callers only need to know which condition happened:
`var ErrNotFound = errors.New("user: not found")`, checked with `errors.Is(err, ErrNotFound)`.
- Custom type when callers need data about the failure:
```go
type ValidationError struct {
Field string
Reason string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("invalid %s: %s", e.Field, e.Reason)
}
// Callers, Go 1.26+:
if ve, ok := errors.AsType[*ValidationError](err); ok {
respondBadRequest(w, ve.Field, ve.Reason)
}
// Before Go 1.26:
var ve *ValidationError
if errors.As(err, &ve) {
respondBadRequest(w, ve.Field, ve.Reason)
}
```
- Compare with `errors.Is`/`errors.As`, never with `==` on wrapped errors or by matching `err.Error()` strings.
- Export only the sentinels and types that callers are expected to handle; every exported one is part of your API.
- Combine independent failures (for example, closing several resources) with `errors.Join`.
## Log or return, not both
Handle each error once. Lower layers wrap and return; the top of the request or job (handler, `main`, worker loop) logs it once with structured context and decides the response.
```go
func (h *Handler) rename(w http.ResponseWriter, r *http.Request) {
err := h.svc.Rename(r.Context(), r.PathValue("id"), r.FormValue("name"))
switch {
case err == nil:
w.WriteHeader(http.StatusNoContent)
case errors.Is(err, ErrNotFound):
http.Error(w, "user not found", http.StatusNotFound)
default:
h.log.ErrorContext(r.Context(), "rename user", "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
}
}
```
The standard `log` package has no `Errorf`; use `log/slog` (`logger.Error(msg, "err", err)`) or the project's logger.
## Deferred cleanup
Do not drop errors from `Close` on files you wrote; they can report a failed flush.
```go
func writeReport(path string, data []byte) (err error) {
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("create report: %w", err)
}
defer func() { err = errors.Join(err, f.Close()) }()
_, err = f.Write(data)
return err
}
```
## Test error paths
Use table-driven tests that assert on error identity, not message text:
```go
tests := []struct {
name string
id string
wantErr error
}{
{"missing user", "nope", ErrNotFound},
{"ok", "u1", nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := svc.Rename(ctx, tt.id, "new")
if !errors.Is(err, tt.wantErr) {
t.Fatalf("Rename() error = %v, want %v", err, tt.wantErr)
}
})
}
```
## Verify before finishing
Run these when they are available in the project:
- `gofmt -l .` (no output) and `go vet ./...`
- `go test ./...`
- `errcheck ./...`, or `golangci-lint run` with `errcheck`, `errorlint` and `wrapcheck` if configured
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.