Advanced Go Concepts
Estimated reading: 3 minutes 26 views

❗ Go – Error Handling Explained with error Interface, Examples & Best Practices (2025 Guide)

🧲 Introduction – How Does Error Handling Work in Go?

Go handles errors explicitly using the built-in error interface. Unlike other languages that use try-catch blocks, Go promotes simple, readable, and predictable error management with multiple return values. This makes error handling concise, type-safe, and easy to track.

🎯 In this section, you’ll learn:

  • What the error type is and how to return errors
  • How to create and handle custom errors
  • Best practices for wrapping and checking errors
  • Real-world use cases with file I/O and validations

✅ Basic Error Handling Syntax

package main

import (
    "errors"
    "fmt"
)

func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 0)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result:", result)
    }
}

📤 Output:

Error: division by zero

✅ Functions return a value and an error. Always check if err != nil.


🧪 Custom Error Messages

err := fmt.Errorf("user %s not found", "john")
fmt.Println(err)

📤 Output:

user john not found

✅ Use fmt.Errorf() to create formatted error strings.


🔁 Wrapping Errors with %w (Go 1.13+)

base := errors.New("connection timeout")
wrapped := fmt.Errorf("fetch failed: %w", base)

if errors.Is(wrapped, base) {
    fmt.Println("Root cause: connection timeout")
}

✅ Use %w to wrap errors and errors.Is() to check the chain.


🧱 Custom Error Types

type NotFoundError struct {
    Resource string
}

func (e NotFoundError) Error() string {
    return fmt.Sprintf("%s not found", e.Resource)
}

func main() {
    err := NotFoundError{"User"}
    fmt.Println(err.Error()) // Output: User not found
}

✅ Implement the Error() method to create custom error types for more control.


🧰 errors.As() – Type Matching

var nf NotFoundError
if errors.As(err, &nf) {
    fmt.Println("It's a NotFoundError:", nf.Resource)
}

✅ Use errors.As() to check and extract specific error types from wrapped chains.


📂 Real-World Example – File Handling

import (
    "fmt"
    "os"
)

func main() {
    _, err := os.Open("nonexistent.txt")
    if err != nil {
        fmt.Println("File error:", err)
    }
}

📤 Output:

File error: open nonexistent.txt: no such file or directory

✅ Standard library functions return descriptive errors.


🚫 Panic vs Error – Key Difference

Featureerrorpanic
UsageExpected failuresUnrecoverable conditions
BehaviorReturns from functionAborts function stack
Recoverable?✅ Yes⚠️ Only with recover()

🧠 Best Practices

PracticeWhy It Helps
✅ Always check for err != nilPrevents silent failures
✅ Use wrapped errors with %wPreserves context
❌ Avoid using panic() unless necessaryPanics are for bugs, not user errors
✅ Return custom error typesEnables more granular handling
✅ Use errors.Is and errors.AsFor robust error chain inspection

📌 Summary – Recap & Next Steps

Go’s error handling model is simple but powerful, promoting explicit, clear error checks at every level of your program. It supports wrapping, custom types, and robust diagnostics without relying on exceptions.

🔍 Key Takeaways:

  • Go uses error interface and explicit return values
  • Use errors.New() or fmt.Errorf() to create errors
  • Use %w, errors.Is(), and errors.As() for chaining and inspection
  • Avoid panics except for truly exceptional cases

⚙️ Next: Explore Go Panic & Recover, Logging Strategies, or how to build a custom error stack utility.


❓ FAQs – Go Error Handling

❓ Is error handling mandatory in Go?
✅ Yes. Ignoring errors leads to bugs. Always check if err != nil.

❓ How do I create custom errors in Go?
✅ Implement the error interface using a struct and the Error() method.

❓ What does %w do in fmt.Errorf()?
✅ It wraps the underlying error, allowing you to trace the root cause later.

❓ Should I use panic to return errors?
❌ No. Use panic only for unexpected, unrecoverable issues.

❓ What’s the difference between errors.Is and errors.As?
errors.Is() checks for equality in wrapped errors. errors.As() checks for specific error types.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Go – Error Handling

Or Copy Link

CONTENTS
Scroll to Top