Node.js Error Handling

Node.js Error Handling – SyntaxError

Making our way through the twists and turns of our full Node.js Error Handling series, today we’ll be checking out the SyntaxError in Node. As with nearly ever other programming language on the market, a Node SyntaxError indicates that a code statement could not be correctly parsed, which means that the executor has no way of determining the intent behind the code. This usually happens as a result of typos, but the actual error messages associated with SyntaxErrors can be fairly vague and not all that useful.

In this article we’ll examine the Node SyntaxError by first looking at where it resides in the larger Node.js Error Class Hierarchy. We’ll then examine four different functional code samples, each of which demonstrate the current techniques of code evaluation that can potentially throw Node SyntaxErrors, so let’s get to it!

The Technical Rundown

Most Node.js errors inherit from the Error base class, or extend from an inherited class therein. The full error hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

As mentioned, a SyntaxError will be thrown when evaluating code that doesn’t make lexical sense to the interpreter. For example, this may occur because an expected token is missing between two values: x + y is a completely valid statement, while neglecting the + between would result in a SyntaxError.

In Node (and JavaScript above it), it is only possible to throw a SyntaxError within evaluated code. Code evaluation is the practice of taking a collection of code from another context (such as a String or an outside script file) and evaluating it inline, during execution of another script. For example, the built-in eval() function can be used for exactly this purpose, by evaluating a passed String argument as JavaScript code. In Node.js there are four possible forms of code evaluation that can throw SyntaxErrors: eval(...), new Function(...), vm, or require(...). We’ll examine each of these scenarios one at a time in the small code samples found below.

We start with the Function constructor, which is a special keyword that allows functions to be created and evaluated inline using the new Function([arg1[, arg2[, ...argN]],] functionBody) syntax, as if creating a new instance of any other class:

The functionTest (x, y, body) function creates a new Function(...) and assigns it to the f local variable, which is then executed within the logging.log(...) call to output the result to the console. Consequently, calling functionTest(x, y, body) evaluates the body argument as the body of the new Function(...). We’ll test this out with two different calls to this Function test function:

Executing these tests produces the following output:

Unsurprisingly, the first invocation with a body of 'return x * y' works properly, while a body of 'return x y' is missing a token between the two parameters, so a SyntaxError is thrown.

Next up let’s look at the evalTest(body) function, which tests the eval() built-in function by evaluating the passed body string code:

Here’s the test calls we’re making:

And this is the output that is produced:

There’s a clear (and intentional) pattern forming here: The first of the test pairs works, while the second fails with some kind of SyntaxError.

Our third test function is requireTest(x, y, path), which invokes the require(...) built-in function to require the code file passed via the path parameter. In this case, it expects an exported function called multiply, so it grabs that value and uses it in a function call with the passed x and y parameters to output the multiplication result:

Since we’re requiring outside files here this example requires a bit more code, found within two separate files. The first file is multiply.js:

And the second is multiply_broken.js:

We now invoke the requireTest(x, y, body) function twice, once for each outside context file:

This results in the following output:

As we can see, the multiply.js file contains no syntax issues, so it functions as expected, Meanwhile, the multiply_broken.js file contains an invalid token between return x and y;, so it throws a SyntaxError.

The final scenario in which Node.js can throw a SyntaxError is using the built-in vm module, which the ability to compile and run code in a V* Virtual Machine context. After requiring the module at the top of the file, our vmTest(body) function handles the testing:

Just as we saw with the evalTest(body) function, vmTest(body) merely attempts to execute the passed body parameter String code in the current context and logs the result. Invoking this function occurs below:

Once again, the first invocation works properly, while the second contains an invalid token between the numerals, resulting in a thrown SyntaxError:

Airbrake’s robust error monitoring software provides real-time error monitoring and automatic error reporting for all your development projects. Airbrake’s state of the art web dashboard ensures you receive round-the-clock status updates on your application’s health and error rates. No matter what you’re working on, Airbrake easily integrates with all the most popular languages and frameworks. Plus, Airbrake makes it easy to customize error parameters, while giving you complete control of the active error filter system, so you only gather the errors that matter most.

Check out Airbrake’s error monitoring software today and see for yourself why so many of the world’s best engineering teams use Airbrake to revolutionize their exception handling practices!