Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Catching exceptions from less parser in node.js

Catching exceptions from less parser in node.js

Problem

I use less with node.js and I'm not so happy about it when it comes to error handling. My code looks like this:

parser.parse(data, function (err, tree) {
    if(err){
      console.log(err);
      res.send(500);
    }else{
      res.header('Content-Type', 'text/css');
      res.send(tree.toCSS());
    }
  });

My problem is that if one of my less files has a Syntax Error, and exception is thrown, crashing the process. Wrapping the Function call in a try block doesn't help. Is it possible to make the process fail more gracefully when there's an error in a less file?

Problem courtesy of: Jørgen

Solution

From what I see in the less.js source, the parse() function should never throw an exception because of a syntax error, but the toCSS() function could.

parser.parse(data, function (parseError, tree) {
  var css;

  if (parseError) {
    console.log(parseError);
    res.send(500);
  } else {
    res.header('Content-Type', 'text/css');
    try {
      css = tree.toCSS();
      res.send(css);
    } catch (ex) {
      console.log(ex);
      res.send(500);
    }
  }
});
Solution courtesy of: Tomalak

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Catching exceptions from less parser in node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×