Improve error handling to prevent corrupted buffer