Catch sync and async errors with Promise.try
Wrap callbacks that may throw or return a promise and handle both failures with one catch handler.
A plugin callback can reject its promise or throw before it returns one. Use Promise.try to handle both failures with one .catch().
Pass the callback without calling it first
Promise.resolve(callback()) looks like it puts the whole call inside a promise. JavaScript evaluates the arguments first. If the callback throws during that evaluation, it never reaches Promise.resolve, so the .catch() on that expression never attaches.
Promise.try takes the function and its arguments and calls the function. A throw rejects the resulting promise. For a normal return, the resulting promise adopts the returned promise or fulfills with the value.
Save each example as an .mjs file and run it with Node 24 or another runtime that supports Promise.try.
function loadLabel(id) {
if (!id) throw new Error('Missing id')
if (id === 'offline') return Promise.reject(new Error('Offline'))
return Promise.resolve(`Label for ${id}`)
}
for (const id of ['', 'offline', 'trail']) {
await Promise.try(loadLabel, id)
.then((label) => console.log(label))
.catch((error) => console.log(error.message))
}The loop prints Missing id, Offline and Label for trail on separate lines.
Pass loadLabel itself. Writing Promise.try(loadLabel(id)) calls it too early and brings back the synchronous throw. A closure such as () => cache.load(id) also works and keeps the receiver if you need to call a method.
Check when the callback starts
Promise.try invokes the callback during the call to Promise.try. Your .then() handler still runs as a promise reaction. That distinction matters if the callback has an observable side effect as soon as it starts.
const result = Promise.try(() => console.log('callback'))
console.log('after Promise.try')
await result.then(() => console.log('reaction'))The callback logs first, then after Promise.try, then reaction.
If a target runtime lacks Promise.try, you can defer the call with Promise.resolve().then(() => loadLabel(id)). That catches both kinds of failure and schedules the callback in a microtask after the current call finishes.