How to Log and Handle Errors Properly in Go

Log errors with context using log.Printf and handle them by returning or exiting to prevent silent failures.

Log errors immediately upon detection using log.Printf with the error message and context, then handle them by returning the error to the caller or terminating the program if unrecoverable. For structured logging in production, use the log/slog package to include timestamps and levels.

package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	file, err := os.Open("data.txt")
	if err != nil {
		log.Printf("failed to open file: %v", err)
		os.Exit(1)
	}
	defer file.Close()
	fmt.Println("File opened successfully")
}