OpenNHP/opennhp · error

file path cannot be empty

Error message

file path cannot be empty

What it means

SaveStructAsJsonFile requires a non-empty filePath; an empty string returns 'file path cannot be empty' before marshaling. This prevents os.WriteFile from failing with a confusing path error at the write stage.

Solutions

  1. Ensure the path is computed/loaded before the call and fail earlier with context
  2. Validate config at startup: required output path field present and non-empty
  3. Use filepath.Join with a guaranteed base directory constant

Example fix

// before
SaveStructAsJsonFile(cfg.TAPath, payload) // cfg.TAPath == ""
// after
if cfg.TAPath == "" { return fmt.Errorf("ta_path missing in config") }
SaveStructAsJsonFile(cfg.TAPath, payload)
Defensive patterns

Strategy: validation

Validate before calling

if filePath == "" { return fmt.Errorf("output path required") }
if dir := filepath.Dir(filePath); dir != "." { if err := os.MkdirAll(dir, 0o755); err != nil { return err } }

Try / catch

if err := SaveStructAsJsonFile(path, data); err != nil { return fmt.Errorf("write %q: %w", path, err) }

Prevention

When it happens

Trigger: Calling SaveStructAsJsonFile("", data) — typically when a path variable was never set, a template/config field for the output path is missing, or a Join of empty components yielded "".

Common situations: Missing config field specifying output directory; filepath.Join with all-empty parts; refactor left a hardcoded path removed.

Understand the failure class

Background: "must not be empty", "cannot be empty" — required-field validation errors across open-source libraries — this error's family across 41 libraries.

Related errors


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

Appendix: source

Thrown at nhp/utils/utils.go:117

	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
}

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

View on GitHub (pinned to 6e04ca5ff0)