Refactor print error substring function