Panic

Our example demonstrates the usage of panic to handle unexpected errors.

A panic typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn’t occur during normal operation or that we aren’t prepared to handle gracefully.

We’ll use panic throughout this site to check for unexpected errors. This is the only program on the site designed to panic.

function main() {
    throw new Error("a problem");
}

A common use of panic is to abort if a function returns an error value that we don’t know how to (or want to) handle. Here’s an example of panicking if we get an unexpected error when creating a new file.

const fs = require('fs');

function main() {
    // Uncomment the next line to see the program panic
    // throw new Error("a problem");

    try {
        fs.writeFileSync('/tmp/file', 'data');
    } catch (err) {
        throw new Error(err);
    }
}

main();

Running this program will cause it to panic, print an error message, and exit with a non-zero status.

$ node panic.js
Error: a problem
    at Object.<anonymous> (/path/to/panic.js:2:11)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    ...

Note that unlike some languages which use exceptions for handling of many errors, in JavaScript, it is idiomatic to use error-indicating return values or promises wherever possible.