@ehrelein/nothrow
Version:
Type-safe error handling
107 lines (105 loc) • 2.74 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// lib.ts
var lib_exports = {};
__export(lib_exports, {
Err: () => Err,
Ok: () => Ok,
safeCall: () => safeCall,
wrap: () => wrap
});
module.exports = __toCommonJS(lib_exports);
function Ok(value) {
return {
ok: true,
invert: null,
value,
flat: value,
map(fn) {
try {
const temp = fn(this.value);
return Ok(temp);
} catch (e) {
return Err(e instanceof Error ? e : new Error(String(e)));
}
},
log(start, end) {
console.log(String(this.flat).slice(start, end));
return this;
},
slice(start, end) {
return String(this.flat).slice(start, end);
}
};
}
function Err(error) {
const err = error instanceof Error ? error : new Error(error);
const uni = error instanceof Error ? error.message : error;
return {
ok: false,
invert: true,
error: err,
flat: uni,
map() {
return this;
},
log(start, end) {
console.log(String(this.flat).slice(start, end));
return this;
},
slice(start, end) {
return String(this.flat).slice(start, end);
}
};
}
function safeCall(fn, ...args) {
try {
const out = fn(...args);
if (out instanceof Promise) {
return out.then((v) => Ok(v)).catch(
(e) => Err(e instanceof Error ? e : new Error(String(e)))
);
}
return Ok(out);
} catch (e) {
return Err(e instanceof Error ? e : new Error(String(e)));
}
}
function wrap(fn) {
return ((...args) => {
try {
const out = fn(...args);
if (out instanceof Promise) {
return out.then((v) => Ok(v)).catch(
(e) => Err(e instanceof Error ? e : new Error(String(e)))
);
}
return Ok(out);
} catch (e) {
return Err(e instanceof Error ? e : new Error(String(e)));
}
});
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Err,
Ok,
safeCall,
wrap
});