brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Promise.try() turns a sync throw into a rejected promise

Javascript
~/tips/tip-js-promise-try-sync-errors

if (!name) throw new Error("No name given"); // sync throw

Handle errors from functions that might be sync or async in one catch.

When a function sometimes returns a promise and sometimes throws right away, a .catch() only handles half of the failures. Promise.try() wraps the call so every error ends up in the same place.

function loadConfig(name) {
  if (!name) throw new Error("No name given");   // sync throw
  return fetch(`/config/${name}.json`).then((r) => r.json());
}

Promise.try(loadConfig, "")
  .then(useConfig)
  .catch((err) => console.error("Config failed:", err.message));
// Config failed: No name given

Calling loadConfig("").catch(...) directly would throw before there is any promise to catch on. Promise.try(fn, ...args) calls the function with the arguments, and whatever happens (a value, a promise or a thrown error) comes back as a promise. Extra arguments after the function are passed on to it.

The older workaround was Promise.resolve().then(() => fn()). That also catches the throw, but runs the function later, in a microtask. Promise.try runs it right away, which keeps the order of side effects as you wrote it.

Inside an async function I do not need it: await in a try block already catches both kinds. It is for promise chains and library code that accepts callbacks from others.

It is fairly new: Chrome 128, Firefox 134, Safari 18.2 and Node.js 23, so check your targets before using it.

Further reading: MDN: Promise.try()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link