Refactoring template instantiation error handling

This is a separated pull request from #1660, that contains refactoring changes only.