Is there any alternative to Bluebird's Promise.try
function. As I'm using async/await
not interested in adding bluebird dependency.
Is there a better way to capture asynchronous error
in Node.JS
await Promise.try(async function() {
// Some code with async operations like readline
await this.nextCall(batchData, true);
}).catch(async function(err) {
// My error handling
});
Any inbuilt functions in Node.js 10.x ?
UPDATE :
Is there a better way to capture asynchronous error
in Node.JS
try {
let interfaceVal = lineReader.createInterface({
input: fs.createReadStream(filePath)
});
interfaceVal.on('line', async (line) => {
throw new Error('My custom Error');
});
// some sync operations
} catch(e) {
// This catch wont get called with custom error
console.log(e);
}
Any idea to capture such asynchronous errors ?
Promise.try
is on its way for specification. Here is the polyfill:This polyfill supports promise subclassing and other features. This is safe to polyfill in Node.js.
You don't need to specify a
catch
clause explicitely in an async function, because it uses the natural Error semantics. Here your functionoperation_A
throws an error, becauseoperation_B
rejected.In nodeJs, if you're using async/await you can use plain try catch blocks and it will catch your errors (and it will work for async calls)
this function definition needs to be declared as
async
There is no reason to wrap
async
function withPromise.try
. The purpose ofPromise.try
is to handle both synchronous errors and rejections similarly:This is already done with
async
since it always returns a promise.This can be used at top level with
async
IIFE:Or in case
async
is nested it can be omitted, a rejection can be handled in parentasync
function withtry..catch
, as another answer explains.In this case an error can be caught only inside
async
function:The use of non-promise API (Node stream) doesn't allow for error handling with promises. Stream callback ignores rejected promises and doesn't allow to propagate the error outside the stream.
Callbacks can be converted to promises only when they are expected to be called
once
. This is not the case withline
. In this case asynchronous iterator can be used, this one of its use cases.Event emitter can be converted to async iterator with
p-event
and iterated withfor await of
insideasync
function: