Fix traceback in template error detection code

Fixes #5081