Package Exports
- die-statement
- die-statement/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (die-statement) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
die() - Because Sometimes Code Needs to Just... Stop
A simple and easy way to kill any application whenever you want, be it on a new line or as an inline statement!
Installation
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;
})();
}Usage
die(message?)Parameters
message(string, optional): Your last words before everything crashes. Defaults to"Fatal Error"if you're feeling uncreative.
Returns
Nothing. It throws an Error. Your code stops here. Game over.
Examples
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.");What It Does
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
Why Use This?
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.
Notes
- 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