Improve stack trace handling logic.