P
P
Pavel2016-05-05 11:10:15
JavaScript
Pavel, 2016-05-05 11:10:15

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 tryhow best to put it to solve two problems:

  1. Clearly see which key was not transmitted
  2. To keep js running

I would be grateful for code examples, thanks.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill, 2016-05-05
@Carduelis

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); }

In this case, if the necessary keys were not transferred, the error will be quite sane:
ReferenceError: data is not defined
    at eval (lodash.templateSources[1]:9:5

By the way, compiling a template is a rather resource-intensive operation, it is best to do it once - the first time you use the template or load it.

V
Vit, 2016-05-05
@fornit1917

It is better to validate the received data before passing it to the template engine

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question