2
votes

I'm creating a client-side handlebar's template editor. Basically you get half of the screen filled with a text editor and the other half with a preview window. The content from the text editor gets logged into the preview window after it has been parsed by handlebars.js, applying some variables in the process.

Whenever I make any syntax error using a handlebar's expression (like typing {name}} instead of {{name}}), a console message appears in DevTools. These messages might look like this:

Parse error on line 4:
...m"><p>Hola, {{name}</p></div></body>
---------------------^
Expecting 'CLOSE_RAW_BLOCK', 'CLOSE', 'CLOSE_UNESCAPED', 'OPEN_SEXPR', 'CLOSE_SEXPR', 'ID', 'OPEN_BLOCK_PARAMS', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', 'SEP', got 'INVALID'

I want to be able to detect whether this errors fire or not, and display the error message in order to warn the user. I've tried unsuccesfully to rewrite javascript Error() class, but it throws all kind of errors and handlebars crashes. Is there any way to get access to these errors?

1

1 Answers

3
votes

You could catch the error and then display it. Something like this:

var template = Handlebars.compile('<p>Hola, {{name}</p>');
try {
  template();
} catch (error) {
  var encodedError = error.message.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
    return '&#' + i.charCodeAt(0) + ';';
  });
  document.write('<pre>' + encodedError + '</pre>');
}
<script src="https://s3.amazonaws.com/builds.handlebarsjs.com/handlebars.min-v4.7.7.js"></script>

(Btw, here's where I borrowed that html entity encoding from.)