0
0
GoConceptBeginner · 3 min read

Sentinel Error in Go: What It Is and How to Use It

A sentinel error in Go is a predefined, named error value used to represent a specific error condition that can be checked by comparing errors directly. It acts like a fixed marker to identify particular error cases in your code.
⚙️

How It Works

Imagine you have a special flag that tells you exactly what went wrong in your program. A sentinel error in Go works like that flag. It is a named error variable that you create once and then use everywhere to signal a specific problem.

When your code returns this sentinel error, other parts of your program can check if the error matches that exact flag by comparing it directly. This is like checking if a key fits a lock perfectly, so you know exactly what happened without guessing.

This approach helps keep error handling simple and clear, especially when you want to detect specific errors and respond differently to each.

💻

Example

This example shows how to define a sentinel error and check for it in a function that might fail.

go
package main

import (
	"errors"
	"fmt"
)

// Define a sentinel error
var ErrNotFound = errors.New("item not found")

func findItem(id int) error {
	if id != 1 {
		return ErrNotFound
	}
	return nil
}

func main() {
	err := findItem(2)
	if err == ErrNotFound {
		fmt.Println("Error: The item was not found.")
	} else if err != nil {
		fmt.Println("Some other error occurred.")
	} else {
		fmt.Println("Item found successfully.")
	}
}
Output
Error: The item was not found.
🎯

When to Use

Use sentinel errors when you want to clearly identify specific error cases by name and compare them directly. This is helpful in libraries or packages where you want users to handle certain errors differently.

For example, if your program looks up data and sometimes the data is missing, a sentinel error like ErrNotFound lets callers check for that case easily and decide what to do next.

However, avoid overusing sentinel errors for complex error details; in those cases, wrapping errors with more context or using error types might be better.

Key Points

  • Sentinel errors are fixed, named error values used for easy comparison.
  • They help detect specific error conditions clearly and simply.
  • Defined once and reused throughout your code or package.
  • Best for simple, well-known error cases like "not found" or "permission denied".
  • Not ideal for errors needing rich context or dynamic messages.

Key Takeaways

Sentinel errors are predefined error variables used to mark specific error cases.
You compare sentinel errors directly using == to detect exact error conditions.
They simplify error handling by providing clear, reusable error markers.
Use sentinel errors for common, simple errors like "not found" or "already exists".
For detailed error info, consider error wrapping or custom error types instead.