Answer the question
In order to leave comments, you need to log in
How to catch errors in underscore/lodash templates?
DISCLAIMER. Tips from the category, "you need Angular.js" or "you are doing everything wrong, you need to rewrite it in a normal way", please do not publish. The project is too massive to be changed overnight.
We use lodash.js templates in the project. We render templates from the data sent by the server. There is a debug problem that constantly arises. Sometimes it happens that the server (sometimes not ours and we do not have access to it) does not always return all the necessary keys. Well, or simply, something falls off somewhere, and lodash gives a Reference Error, and then all js does not work.
What is the best way to catch these errors? Basically we use one function where the template is assembled using _.template()().
I guess you can use catch try
how best to put it to solve two problems:
Answer the question
In order to leave comments, you need to log in
I think you are doing everything right. You need to separate template compilation and template execution, and then wrap the execution in try catch
.
let tpl = _.template('<%-data%>');
let html;
try {
html = tpl(params);
} catch (e) { logError(e); }
ReferenceError: data is not defined
at eval (lodash.templateSources[1]:9:5
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question