#966·sonic

fix: replace panic with error return in GetByPath methods

Author: lxcxjxhxCreated Jul 30, 2026Updated Sep 17, 2026

Issue: Improve Error Handling in GetByPath Methods

Problem Description

The sonic library currently uses panic() in several GetByPath methods when encountering invalid path parameter types. This causes the entire program to crash instead of allowing graceful error handling.

Affected Locations

  1. ast/node.go:1019 - GetByPath method
  2. ast/api_compat.go:85 - getByPath method
  3. ast/search.go:81 and ast/search.go:111 - Search and GetByPath methods

Current Behavior

When a user passes a path parameter that is neither int nor string, the library calls panic("path must be either int or string"), which crashes the program.

Expected Behavior

The library should return a proper error that users can handle, rather than panicking. This follows Go's error handling best practices and makes the library more robust for production use.

Proposed Solution

  1. Define a new error type ErrInvalidPathType in ast/parser.go
  2. Replace panic() calls with error returns
  3. Maintain backward compatibility by keeping existing method signatures
  4. Return error nodes or error values instead of panicking

Impact

  • Breaking Change: No - existing method signatures remain unchanged
  • Performance: Negligible - error creation only happens on invalid input
  • Compatibility: Fully backward compatible - existing code continues to work

This change improves the library's reliability and follows Go's idiomatic error handling patterns.