Promises not catching error correctly NodeJS - javascript

If I remember correctly Promises are supposed to catch an error when one is thrown at all times so that Promise.catch() can be used to handle that error. I don't recall any exceptions however when I throw an error inside setTimeout() this somehow doesn't work.
Can someone explain why this doesn't work? Or is it simply a bug in NodeJS?
Test code
// This works!
function async() {
return new Promise(function (resolve, reject) {
throw new Error('test');
});
}
async().catch(function() {
console.log('Ok: 1');
});
// This doesn't work..
function async_fail() {
return new Promise(function (resolve, reject) {
setTimeout(function() {
throw new Error('test');
}, 1);
});
}
async_fail().catch(function() {
console.log('Ok: 2');
});

You will never catch an Error that is thrown in setTimeout, because it executes async to the actual execution of the promise function. So the promise itself already finished (without any call to resolve or reject) when the function inside set timeout is called.
If you want the promise to fail based on an error inside setTimeout you will need to catch it manually and call reject:
setTimeout(function() {
try{
throw new Error('test');
}catch(ex){
reject(ex);
}
}, 1);

Related

How to catch a callback error with a try catch?

I have an async function that grabs the contents of a file, like so:
async function getFile (name) {
return new Promise(function (resolve, reject) {
fs.readFile(`./dir/${name}.txt`, 'utf8', function (error, file) {
if (error) reject(error)
else resolve(file)
})
})
}
And I call that function into a console log
getFile('name').then( console.log )
If I make an error, like misspelling the file name, I get this handy error:
(node:17246) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was not
handled with .catch(). (rejection id: 1)
I can fix it by doing this:
getFile('name').then( console.log ).catch( console.log ) but is there a way to deal with the error within the callback? Perhaps a try catch? How would I do that?
You still need to catch errors that are rejected.
I think it's where you call your getFile function from - that needs to be wrapped in a try/catch block
try {
const result = await getFile('name')
} catch(e) {
... You should see rejected errors here
}
Or, I think this would work for your example:
await getFile('name').then( console.log ).catch(e => {...})
Testing this in the Chrome DevTools console:
async function test () {
return new Promise(function(resolve, reject) {
throw 'this is an error';
})
}
And calling it via the following:
await test().catch(e => alert(e))
Shows that this does, in fact, work!
If I understand correctly, you want your function to resolve regardless of whether you got and error or not. If so you can just resolve in either case:
async function getFile (name) {
return new Promise(function (resolve, reject) {
fs.readFile(`./dir/${name}.txt`, 'utf8', function (error, file) {
if (error) resolve(error)
else resolve(file)
})
})
}
Then you'd need to handle the errors outside, e.g.
getFile('name')
.then(getFileOutput => {
if (getFileOutput instanceof Error) {
// we got an error
} else {
// we got a file
}
})
or
const getFileOutput = await getFile('name');
if (getFileOutput instanceof Error) {
// we got an error
} else {
// we got a file
}
Is that what you're looking for?

How to catch error from Asynchronous code

The following line of code is able to catch the error (as it is sync)
new Promise(function(resolve, reject) {
throw new Error("Whoops!");
}).catch(alert);
But when I modify my code like below
new Promise(function(resolve, reject) {
setTimeout(() => {
throw new Error("Whoops!");
}, 1000);
}).catch(alert);
It is not able to catch the error.
I have a use case where I want to catch this error. How can I achieve it?
Following the link "https://bytearcher.com/articles/why-asynchronous-exceptions-are-uncatchable/" I am able to understand why is it happening. Just want to know is there still any solution to catch such an error.
Kindly note, By the use of setTimeout, I am pointing the use of async call which can give some response or can give error as in my case when I supply incorrect URL in a fetch statement.
fetch('api.github.com/users1') //'api.github.com/user'is correct url
.then(res => res.json())
.then(data => console.log(data))
.catch(alert);
You'll need a try/catch inside the function you're asking setTimeout to call:
new Promise(function(resolve, reject) {
setTimeout(() => {
try {
throw new Error("Whoops!"); // Some operation that may throw
} catch (e) {
reject(e);
}
}, 1000);
}).catch(alert);
The function setTimeout calls is called completely independently of the promise executor function's execution context.
In the above I've assumed that the throw new Error("Whoops!") is a stand-in for an operation that may throw an error, rather than an actual throw statement. But if you were actually doing the throw, you could just call reject directly:
new Promise(function(resolve, reject) {
setTimeout(() => {
reject(new Error("Whoops!"));
}, 1000);
}).catch(alert);
Use reject to throw the error,
new Promise(function(resolve, reject) {
setTimeout(() => {
reject(new Error("Whoops!"))
}, 1000);
}).catch(alert);
To handle errors, put the try-catch inside the setTimeout handler:
new Promise(function(resolve, reject) {
setTimeout(() => {
try{
throw new Error("Whoops!");
}catch(alert){
console.log(alert);
}
}, 1000);
});
You could also use a little utility:
function timeout(delay){
return new Promise(resolve => setTimeout(resolve, delay));
}
timeout(1000)
.then(() => {
throw new Error("Whoops!");
})
.catch(alert);

Unable to handle errors in javascript promise

Why doesn't it run the code "console.log(err)" below? but instead returns "TypeError: Cannot create property 'uncaught' on string 'error in promise'"
function abc() {
throw "error in promise";
return 123;
};
abc().catch(function(err) {
console.log(err)
}).then ( abcMessage =>
console.log(abcMessage)
)
.then and .catch require a Promise to be constructed. You are not returning a promise. The promise callback (executor) takes two arguments, a resolver, and a rejecter. Depending on what happens in the code, you may need to call resolve if everything goes right, or reject if something goes wrong.
function abc() {
return new Promise(function(resolve, reject) {
reject(123)
});
};
abc()
.catch(err => {
console.log(err);
return err;
})
.then(abcMessage => {
console.log(abcMessage)
});
new Error("error in promise")

Why does my Promise fall with error? [duplicate]

What is the best way to handle this scenario. I am in a controlled environment and I don't want to crash.
var Promise = require('bluebird');
function getPromise(){
return new Promise(function(done, reject){
setTimeout(function(){
throw new Error("AJAJAJA");
}, 500);
});
}
var p = getPromise();
p.then(function(){
console.log("Yay");
}).error(function(e){
console.log("Rejected",e);
}).catch(Error, function(e){
console.log("Error",e);
}).catch(function(e){
console.log("Unknown", e);
});
When throwing from within the setTimeout we will always get:
$ node bluebird.js
c:\blp\rplus\bbcode\scratchboard\bluebird.js:6
throw new Error("AJAJAJA");
^
Error: AJAJAJA
at null._onTimeout (c:\blp\rplus\bbcode\scratchboard\bluebird.js:6:23)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
If the throw occurs before the setTimeout then bluebirds catch will pick it up:
var Promise = require('bluebird');
function getPromise(){
return new Promise(function(done, reject){
throw new Error("Oh no!");
setTimeout(function(){
console.log("hihihihi")
}, 500);
});
}
var p = getPromise();
p.then(function(){
console.log("Yay");
}).error(function(e){
console.log("Rejected",e);
}).catch(Error, function(e){
console.log("Error",e);
}).catch(function(e){
console.log("Unknown", e);
});
Results in:
$ node bluebird.js
Error [Error: Oh no!]
Which is great - but how would one handle a rogue async callback of this nature in node or the browser.
Promises are not domains, they will not catch exceptions from asynchronous callbacks. You just can't do that.
Promises do however catch exceptions that are thrown from within a then / catch / Promise constructor callback. So use
function getPromise(){
return new Promise(function(done, reject){
setTimeout(done, 500);
}).then(function() {
console.log("hihihihi");
throw new Error("Oh no!");
});
}
(or just Promise.delay) to get the desired behaviour. Never throw in custom (non-promise) async callbacks, always reject the surrounding promise. Use try-catch if it really needs to be.
After dealing with the same scenario and needs you are describing, i've discovered zone.js , an amazing javascript library , used in multiple frameworks (Angular is one of them), that allows us to handle those scenarios in a very elegant way.
A Zone is an execution context that persists across async tasks. You can think of it as thread-local storage for JavaScript VMs
Using your example code :
import 'zone.js'
function getPromise(){
return new Promise(function(done, reject){
setTimeout(function(){
throw new Error("AJAJAJA");
}, 500);
});
}
Zone.current
.fork({
name: 'your-zone-name',
onHandleError: function(parent, current, target, error) {
// handle the error
console.log(error.message) // --> 'AJAJAJA'
// and return false to prevent it to be re-thrown
return false
}
})
.runGuarded(async () => {
await getPromise()
})
Thank #Bergi. Now i know promise does not catch error in async callback. Here is my 3 examples i have tested.
Note: After call reject, function will continue running.
Example 1: reject, then throw error in promise constructor callback
Example 2: reject, then throw error in setTimeout async callback
Example 3: reject, then return in setTimeout async callback to avoid crashing
// Caught
// only error 1 is sent
// error 2 is reached but not send reject again
new Promise((resolve, reject) => {
reject("error 1"); // Send reject
console.log("Continue"); // Print
throw new Error("error 2"); // Nothing happen
})
.then(() => {})
.catch(err => {
console.log("Error", err);
});
// Uncaught
// error due to throw new Error() in setTimeout async callback
// solution: return after reject
new Promise((resolve, reject) => {
setTimeout(() => {
reject("error 1"); // Send reject
console.log("Continue"); // Print
throw new Error("error 2"); // Did run and cause Uncaught error
}, 0);
})
.then(data => {})
.catch(err => {
console.log("Error", err);
});
// Caught
// Only error 1 is sent
// error 2 cannot be reached but can cause potential uncaught error if err = null
new Promise((resolve, reject) => {
setTimeout(() => {
const err = "error 1";
if (err) {
reject(err); // Send reject
console.log("Continue"); // Did print
return;
}
throw new Error("error 2"); // Potential Uncaught error if err = null
}, 0);
})
.then(data => {})
.catch(err => {
console.log("Error", err);
});

Promise constructor with reject call vs throwing error

In the following code:
var p1 = new Promise(function (resolve, reject) {
throw 'test1';
});
var p2 = new Promise(function (resolve, reject) {
reject('test2');
});
p1.catch(function (err) {
console.log(err); // test1
});
p2.catch(function (err) {
console.log(err); // test2
});
Is there any difference between using reject (in p2) from the Promise api, and throwing an error (in p1) using throw?
Its exactly the same?
If its the same, why we need a reject callback then?
Is there any difference between using reject (in p2) from the Promise api, and throwing an error (in p1) using throw?
Yes, you cannot use throw asynchronously, while reject is a callback. For example, some timeout:
new Promise(_, reject) {
setTimeout(reject, 1000);
});
Its exactly the same?
No, at least not when other code follows your statement. throw immediately completes the resolver function, while calling reject continues execution normally - after having "marked" the promise as rejected.
Also, engines might provide different exception debugging information if you throw error objects.
For your specific example, you are right that p1 and p2 are indistinguishable from the outside.
I know this is a bit late, but I don't really think either of these answers completely answers the questions I had when I found this, Here is a fuller example to play with.
var p1 = new Promise(function (resolve, reject) {
throw 'test 1.1'; //This actually happens
console.log('test 1.1.1'); //This never happens
reject('test 1.2'); //This never happens because throwing an error already rejected the promise
console.log('test 1.3'); //This never happens
});
var p2 = new Promise(function (resolve, reject) {
reject('test 2.1'); //This actually happens
console.log('test 2.1.1'); //This happens BEFORE the Promise is rejected because reject() is a callback
throw 'test 2.2'; //This error is caught and ignored by the Promise
console.log('test 2.3'); //This never happens
});
var p3 = new Promise(function (resolve, reject) {
setTimeout(function() { reject('test 3.1');}, 1000); //This never happens because throwing an error already rejected the promise
throw('test 3.2'); //This actually happens
console.log('test 3.3'); //This never happens
});
var p4 = new Promise(function (resolve, reject) {
throw('test 4.1'); //This actually happens
setTimeout(function() { reject('test 4.2');}, 1000); //This never happens because throwing an error already rejected the promise
console.log('test 4.3'); //This never happens
});
var p5 = new Promise(function (resolve, reject) {
setTimeout(function() { throw('test 5.1');}, 1000); //This throws an Uncaught Error Exception
reject('test 5.2'); //This actually happens
console.log('test 5.3'); //This happens BEFORE the Promise is rejected because reject() is a callback
});
var p6 = new Promise(function (resolve, reject) {
reject('test 6.1'); //This actually happens
setTimeout(function() { throw('test 6.2');}, 1000); //This throws an Uncaught Error Exception
console.log('test 6.3'); //This happens BEFORE the Promise is rejected because reject() is a callback
});
p1.then(function (resolve) {
console.log(resolve, "resolved")
}, function (reject) {
console.log(reject, "rejected")
}).catch(function (err) {
console.log(err, "caught"); // test1
});
p2.then(function (resolve) {
console.log(resolve, "resolved")
}, function (reject) {
console.log(reject, "rejected")
}).catch(function (err) {
console.log(err, "caught"); // test2
});
p3.then(function (resolve) {
console.log(resolve, "resolved")
}, function (reject) {
console.log(reject, "rejected")
}).catch(function (err) {
console.log(err, "caught"); // test3
});
p4.then(function (resolve) {
console.log(resolve, "resolved")
}, function (reject) {
console.log(reject, "rejected")
}).catch(function (err) {
console.log(err, "caught"); // test4
});
p5.then(function (resolve) {
console.log(resolve, "resolved")
}, function (reject) {
console.log(reject, "rejected")
}).catch(function (err) {
console.log(err, "caught"); // test5
});
p6.then(function (resolve) {
console.log(resolve, "resolved")
}, function (reject) {
console.log(reject, "rejected")
}).catch(function (err) {
console.log(err, "caught"); // test6
});
No, there is not, the two are completely identical. The only difference and why we need reject is when you need to reject asynchronously - for example if you're converting a callback based API it might need to signal an asynchronous error.
var p = new Promise(function(resolve, reject){
someCallbackApi(function(err, data){
if(err) reject(err); // CAN'T THROW HERE, non promise context, async.
else resolve(data);
});
});
A very interesting observation is that if you use throw it will be handled by first the reject handler & then theerror handler if a reject handler is not in place.
With reject handler block
var allowed = false;
var p1 = new Promise(
function(resolve, reject) {
if (allowed)
resolve('Success');
else
// reject('Not allowed');
throw new Error('I threw an error')
})
p1.then(function(fulfilled) {
console.log('Inside resolve handler, resolved value: ' + fulfilled);
}, function(rejected) {
console.log('Inside reject handler, rejected value: ' + rejected);
}).catch(function(error) {
console.log('Inside error handler, error value: ' + error);
})
Without reject handler block
var allowed = false;
var p1 = new Promise(
function(resolve, reject) {
if (allowed)
resolve('Success');
else
// reject('Not allowed');
throw new Error('I threw an error')
})
p1.then(function(fulfilled) {
console.log('Inside resolve handler, resolved value: ' + fulfilled);
}).catch(function(error) {
console.log('Inside error handler, error value: ' + error);
})
Additionally, the catch block will be able catch any error thrown inside the resolve handler.
var allowed = true;
var p1 = new Promise(
function(resolve, reject) {
if (allowed)
resolve('Success');
else
// reject('Not allowed');
throw new Error('I threw an error')
})
p1.then(function(fulfilled) {
console.log('Inside resolve handler, resolved value: ' + fulfilled);
throw new Error('Error created inside resolve handler block');
}).catch(function(error) {
console.log('Inside error handler, error value: ' + error);
})
It looks like it's best to use throw, unless you can't if you are running some async task, you will have to pass the reject callback down to the async function. But there's a work around, that is is to promisifying your async function. More on https://stackoverflow.com/a/33446005

Categories

Resources