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
ast/node.go:1019-GetByPathmethodast/api_compat.go:85-getByPathmethodast/search.go:81andast/search.go:111-SearchandGetByPathmethods
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
- Define a new error type
ErrInvalidPathTypeinast/parser.go - Replace
panic()calls with error returns - Maintain backward compatibility by keeping existing method signatures
- 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.
Source: bytedance/sonic