metaory / pcall.js

🛟 Handle Errors as Values · 📦 Zero-dependency

Home Page:https://npmjs.com/package/pcall.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Pcall.js

logo-of-pcall

🛟 Minimal Protected Asynchronous Operations

╶─ ╴╶ ╴╶ ╴╶ ╴╶ ╴╶ ─╴

  • 🎌 Delegate Promise Resolutions
  • 🧬 Lifecycle Callback Options
  • 📍 Concise and Convenient Signature
  • 📦 Zero-Dependency
  • 🛑 Avoid try/catch ~~HELL~ 👹
  • 🌟 Better Visibility and Control
  • 🌐 Works in Node.js (ESM/CJS) and all modern browsers
  • 〽️ Minimal Obsessive Disorder

🔥 entire lib 🔥

encoded-dist
decoded decoded-dist

Inspiration

Lua approach to error handling is simple yet powerful. ^Lua:5.4 ^Lua:8.4, ^Lua:8.5

🔹 pcall.js is heavily inspired by Lua pcall with superpowers 🦄!


SYNOPSIS

pcall({f}, {arg1}, {...})

pcall() Calls function {f} with the given arguments in protected mode. This means that any error inside {f} is not propagated;

Instead, pcall catches the error and returns a tuple.

Its first element is the status code (a boolean), which is true if the call succeeds without errors. And all results from the call, on second element; [true, {res}]

In case of any error, pcall returns false plus the error message; [false, {err}]


Usage

# install
npm install pcall.js
// ESM
import Pcall from 'pcall.js'

// CJS
const Pcall = require('pcall.js')

Convert

// 🔴 BEFORE
const user = await prisma.users.findFirst({ where: { id: User.id }}, { ctx })

// ✅AFTER
import Pcall from 'pcall.js'
const [err, user] = await Pcall(prisma.users.findFirst, { where: { id: User.id }}, { ctx })

// ✅THROW
err && throw new Error("XYZZY", { cause: err });

Options

// ✅Options
import Pcall from 'pcall.js'

const pcall = new Pcall({
  onSuccess: (args, res) => { /*···*/ },
  onFailure: (args, err) => { /*···*/ },
  cleanup: (args) => { /*···*/ },
  trace: true,
  /* 🚧 serializer/parsers */
})

const [err, user] = await pcall(prisma.users.findFirst, { where: { id: User.id }}, { ctx })

💡 Check test/dev.test.js for more examples


Development

# run test playground in watch mode
npm run dev

# build production
npm run build

# build stub
npm run build:stub

TODO

  • 🌀 Lifecycle Hooks
  • [.] 🔌 Serializer
  • [.] 🧬 Parser
  • [.] 📜 JSDoc
  • [.] 🔧 ESLint
  • [o] 📖 Docs
  • [o] ⚠️ Tests
  • [.] 💡 Examples

License

MIT