A simple and easy way to kill any application whenever you want, be it on a new line or as an inline statement!
npm i die-statementOr just drop the function in your codebase. No npm bloat, no build step, no regrets. Here it is, i'll make it easy for ya!
function die(message = "Fatal Error") {
return (() => {
const error = new Error();
const match = error.stack?.match(/^(?!die).*@(.*:\d+:\d+)$/m);
if (match) {
console.error(message, "\n\nDied at:", match[1]);
} else {
console.error(message, "\n\nDied at (location unknown)");
}
throw error;
})();
}die(message?)message(string, optional): Your last words before everything crashes. Defaults to"Fatal Error"if you're feeling uncreative.
Nothing. It throws an Error. Your code stops here. Game over.
As a fallback (the fancy way):
const necessaryElement = document.getElementById("#important") || die();When you've had enough (the direct way):
if (userDidSomethingDumb) {
die("User did something unforgivable");
}The dramatic exit:
const config = loadConfig() || die("No config, no service. I quit.");When called, die() will:
- Log your message (or the default one) to the console
- Show you exactly where your code gave up on life (
Died at: file.js:42:10) - Throw an Error to stop execution immediately
Sometimes throw new Error() is too many characters. Sometimes you want your failures to feel more... deliberate. Sometimes you just want to watch the world burn, but in a traceable way.
Also, if you've ever missed PHP's die() function and tried to use throw new Error() in a statement only to have JavaScript laugh at you—well, now you don't have to miss it anymore.
- The stack trace parsing works in modern browsers. If it fails, you'll get
"(location unknown)"instead. Evendie()has its limits. - This is blocking and synchronous. If you call it, everything stops. That's the point.
"To die, to sleep—no more—and by a sleep to say we end the heartache..." - Shakespeare, probably talking about JavaScript