Put try/catch block into the replace function.
Also check that template is a string.