phpdie
Version:
|| DIE('reason') Throws an error like PHP 's `OR DIE('REASON')`, Simple error throwing in a functional dev style.
76 lines (73 loc) • 1.78 kB
JavaScript
// catchArgs.ts
function catchArgs(fn) {
return (...args) => {
try {
const r = fn(...args);
const isPromise = typeof r.then === "function";
return !isPromise ? r : async function() {
return await r;
}().catch((error) => handleError(error, args));
} catch (error) {
handleError(error, args);
}
};
}
function handleError(error, args) {
if (error instanceof Error) {
throw Object.assign(error, {
cause: {
...typeof error.cause === "object" && error.cause || null,
...typeof error.cause === "string" && { cause: error.cause } || null,
args
}
});
}
}
// stringifyError.ts
function stringifyError(reason, ...slots) {
if (typeof reason === "string") {
return reason.trim();
}
if (Array.isArray(reason)) {
return reason.map((e, i) => e + (slots[i]?.toString() ?? "")).join("");
}
return String(reason instanceof Error && reason.message || reason);
}
// index.ts
var phpdie_default = DIE;
function DIEError(reason, ...slots) {
throw new Error(stringifyError(reason, ...slots));
}
function DIE(reason, ...slots) {
throw errorFormat(reason, ...slots);
}
function DIES(alert2, ...args) {
alert2(...args);
throw new Error("DIES", { cause: args });
}
var DIEAlert = (...args) => {
alert(stringifyError(...args));
DIE(...args);
};
var DIEProcess = (...args) => {
console.error(stringifyError(...args));
process.exit(1);
};
function errorFormat(reason, ...slots) {
if (typeof reason === "string") {
return reason.trim();
}
if (Array.isArray(reason)) {
return reason.map((e, i) => e + (slots[i] ?? "")).join("");
}
return reason;
}
export {
phpdie_default as default,
catchArgs,
DIES,
DIEProcess,
DIEError,
DIEAlert,
DIE
};