OpenNHP/opennhp · error

data cannot be nil

Error message

data cannot be nil

What it means

SaveStructAsJsonFile refuses to serialize a nil value: if the data parameter is nil it returns 'data cannot be nil' before any file I/O. This guards against writing a literal 'null' JSON file or a confusing marshal outcome. Callers (e.g. registerTAService) must pass a concrete struct/map value.

Solutions

  1. Check the value is non-nil before calling, or return an error upstream instead
  2. Initialize the struct with defaults when source data is missing
  3. Handle the error from SaveStructAsJsonFile rather than ignoring it

Example fix

// before
var taService *TAService // nil after failed lookup
SaveStructAsJsonFile(path, taService)
// after
if taService == nil { return fmt.Errorf("ta service not found") }
SaveStructAsJsonFile(path, taService)
Defensive patterns

Strategy: validation

Validate before calling

if data == nil { return fmt.Errorf("refusing to save nil payload to %s", filePath) }

Type guard

func nonNil(v any) bool { return v != nil }

Try / catch

if err := SaveStructAsJsonFile(path, payload); err != nil { return fmt.Errorf("save ta service: %w", err) }

Prevention

When it happens

Trigger: Passing an untyped nil, a nil pointer of concrete type passed as any and checked as nil only for untyped nil is NOT caught — but direct nil, or a variable that is literally nil (nil map assigned to any interface value is non-nil interface; untyped nil is caught), typically from a failed lookup upstream returning nil data.

Common situations: Upstream API/registry call returned nil and the result was forwarded unchecked to SaveStructAsJsonFile; forgotten struct initialization; error path that skips population of the payload.

Related errors


AI-assisted analysis of OpenNHP/opennhp@6e04ca5ff0 (2026-09-07). Data as JSON: /api/errors/f05b6dffec75593e. Report an issue: GitHub.

Appendix: source

Thrown at nhp/utils/utils.go:114

func GenerateTempFilePath(pattern string) (string, error) {
	file, err := os.CreateTemp("", pattern)
	if err != nil {
		return "", err
	}

	tempPath := file.Name()

	if err := file.Close(); err != nil {
		return "", err
	}

	return tempPath, nil
}

func SaveStructAsJsonFile(filePath string, data any) error {
	if data == nil {
		return fmt.Errorf("data cannot be nil")
	}
	if filePath == "" {
		return fmt.Errorf("file path cannot be empty")
	}

	jsonData, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		return fmt.Errorf("failed to marshal data to JSON: %w", err)
	}

	err = os.WriteFile(filePath, jsonData, 0644) //nolint:gosec // G306: Generic utility - callers determine sensitivity
	if err != nil {
		return fmt.Errorf("failed to write JSON to file: %w", err)
	}

	return nil
}

View on GitHub (pinned to 6e04ca5ff0)