@duydang2311/attempt
Version:
Go-like error handling for JavaScript and TypeScript
85 lines (82 loc) • 2.15 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __moduleCache = /* @__PURE__ */ new WeakMap;
var __toCommonJS = (from) => {
var entry = __moduleCache.get(from), desc;
if (entry)
return entry;
entry = __defProp({}, "__esModule", { value: true });
if (from && typeof from === "object" || typeof from === "function")
__getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
}));
__moduleCache.set(from, entry);
return entry;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, {
get: all[name],
enumerable: true,
configurable: true,
set: (newValue) => all[name] = () => newValue
});
};
// lib/index.ts
var exports_lib = {};
__export(exports_lib, {
attemptSync: () => attemptSync,
attemptOk: () => attemptOk,
attemptFail: () => attemptFail,
attemptAsync: () => attemptAsync,
attempt: () => attempt
});
module.exports = __toCommonJS(exports_lib);
// lib/attempt.ts
var symbol = Symbol("attempt");
var attemptSync = (fn) => {
return (mapException) => {
try {
return attempt.ok(fn());
} catch (e) {
return attempt.fail(mapException ? mapException(e) : e);
}
};
};
var attemptAsync = (fn) => {
return async (mapException) => {
try {
const ret = await fn();
if (isAttempt(ret)) {
return ret;
}
return attempt.ok(ret);
} catch (e) {
return attempt.fail(mapException ? mapException(e) : e);
}
};
};
var attemptOk = (data) => ({
[symbol]: true,
ok: true,
failed: false,
data
});
var attemptFail = (error) => ({
[symbol]: true,
ok: false,
failed: true,
error
});
var attempt = {
sync: attemptSync,
async: attemptAsync,
ok: attemptOk,
fail: attemptFail
};
var isAttempt = (value) => {
return typeof value === "object" && value !== null && symbol in value;
};