How to Handle Errors Idiomatically in Go

Handle errors in Go by checking return values immediately, using errors.Is for specific types, and wrapping errors with fmt.Errorf to preserve context.

Handle errors idiomatically in Go by checking the error return value immediately after a function call and returning or logging it if non-nil. This pattern ensures failures are caught early and propagated correctly up the call stack.

file, err := os.Open("data.txt")
if err != nil {
	return fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()

For specific error types like archive/tar.ErrInsecurePath, use errors.Is to check for the exact error and handle it accordingly:

hdr, err := tr.Next()
if err != nil {
	if errors.Is(err, archive/tar.ErrInsecurePath) {
		log.Println("skipping insecure path")
		continue
	}
	return err
}

When wrapping errors, use fmt.Errorf with the %w verb to preserve the error chain for later inspection.