I am busy working with some code that is responing in an unexpected way (to me). It involves handling Node.js promise exceptions.
I have the following function modified so that all it does is fail
function asynFunc() {
return new Promise(function(res, rej) {
rej("GENERIC ERROR");
});
}
The problem comes in when I am trying to call it and handle this error. If I do the following it works as I expect it to, the function fails and executes the catch which returns, stopping the last console log from executing
async function appStart() {
try {
await asyncFunc();
} catch(log) {
console.log(log);
return;
}
console.log("YOU SHOULD NOT SEE THIS");
}
appStart();
If I write the function as follows though, it does not seem to return, it still executes the last console log regardless of the await
async function appStart() {
await asyncFunc().catch(function(log) {
console.log(log);
return;
});
console.log("YOU SHOULD NOT SEE THIS");
}
If this is doing what I think it's doing then the return is returning from the function inside of the catch and not the appStart function itself, or I'm completely wrong in which case I have no idea why it's not returning.
Is there a way to use the second catch method and still have it return from the calling function?
In the second example, you are not returning from the outside function in the catch, you are returning from the catch callback:
await asyncFunc().catch(function(log) {
console.log(log);// ^
return; // | returns from that function
});
This has the effect of catching the error and moving on and returning a new promise resolving to undefined. There is no way to control the return of the outside function from inside the callback. You need to test the result of the async operation from the outside function, which leaves you with try/catch or explicitly testing the result after the promise resolves.
You're right. It's returning only inside the catch callback, not the outer async function. That's why it exits the catch callback and resolves, and then logs "YOU SHOULD NOT SEE THIS". Generally, it's very unreadable if you mix promise then and catch chaining along with async/await and try/catch. Pick one and stick with it, because mixing them may lead to the inability to catch and handle errors seamlessly.
Related
I'm hoping someone can suggest a better method for what I'm trying to achieve.
While performing a rather long and complicated webflow using puppeteer, occasionally an error will occur that disrupts the actions I'm trying to take on the page. There's nothing I can do about it in these situations other than return a useful error. However it doesn't happen often enough to explicitly wait and try to catch it after each step in my code.
The solution I have is:
async function runCode() {
try {
const page = browser.open(url)
listenForError(page)
await longWebFlow()
} catch (err) {
return err.message
}
}
async function listenForError(page) {
await page.waitForXPath(errorMessageXPath)
throw new Error('Error found!')
}
try {
await runCode()
} catch (err) {
console.log(err.message)
// should print('Error found')
}
Obviously, the unawaited listenForError call won't be caught in the try/catch, but I also cant await the call, or else I'll never get to the main part of the code.
The code works to short-circuit the process and return, since the error occurred, but how can I refactor this to catch the error message?
It seems like you want to wait until either the error is thrown or the longWebFlow() finishes - basically doing both concurrently. That's a perfect use case for promises with Promise.race:
async function runCode() {
const page = browser.open(url)
await Promise.race([
listenForError(page),
longWebFlow(),
]);
}
You could also use Promise.all if you made longWebFlow cancel the listenForError and fulfill the promise.
Either way, since you can properly await the promises now, the error also will be caught in the try/catch, as it should.
If you can't await the async operation then the only other "follow up" is with callbacks like .then() and .catch(). For example, you can catch the error here:
listenForError(page).catch(e => console.log(e));
This won't await the operation, it's just supplying a callback for whenever that operation fails at whatever point in the future.
const errorTest = async() => {
const result = await $.get("http://dataa.fixer.io/api/latest?access_key=9790286e305d82fbde77cc1948cf847c&format=1");
return result;
}
try {
errorTest()
}
catch(err) {
console.log("OUTSIDE ERROR!" + err)
}
The URL is intentionally incorrect to throw an error, but the outside catch() it not capturing it. Why?
If I use then() and catch() instead, it works.
errorTest()
.then(val=> console.log(val))
.catch(err=> console.error("ERROR OCCURRED"))
This works, but the try {..} catch() doesn't. Why?
I keep getting the Uncaught (in promise) error.
async function errorTest() { /* ... */ }
try {
errorTest()
}
catch(err) {
console.log("OUTSIDE ERROR!" + err)
}
Because errorTest is async, it will always return a promise and it is never guaranteed to finish execution before the next statement begins: it is asynchronous. errorTest returns, and you exit the try block, very likely before errorTest is fully run. Therefore, your catch block will never fire, because nothing in errorTest would synchronously throw an exception.
Promise rejection and exceptions are two different channels of failure: promise rejection is asynchronous, and exceptions are synchronous. async will kindly convert synchronous exceptions (throw) to asynchronous exceptions (promise rejection), but otherwise these are two entirely different systems.
(I'd previously written that async functions do not begin to run immediately, which was my mistake: As on MDN, async functions do start to run immediately but pause at the first await point, but their thrown errors are converted to promise rejections even if they do happen immediately.)
function errorTest() {
return new Promise(/* ... */); // nothing throws!
}
function errorTestSynchronous() {
throw new Error(/* ... */); // always throws synchronously
}
function errorTestMixed() {
// throws synchronously 50% of the time, rejects 50% of the time,
// and annoys developers 100% of the time
if (Math.random() < 0.5) throw new Error();
return new Promise((resolve, reject) => { reject(); });
}
Here you can see various forms of throwing. The first, errorTest, is exactly equivalent to yours: an async function works as though you've refactored your code into a new Promise. The second, errorTestSynchronous, throws synchronously: it would trigger your catch block, but because it's synchronous, you've lost your chance to react to other asynchronous actions like your $.get call. Finally, errorTestMixed can fail both ways: It can throw, or it can reject the promise.
Since all synchronous errors can be made asynchronous, and all asynchronous code should have .catch() promise chaining for errors anyway, it's rare to need both types of error in the same function and it is usually better style to always use asynchronous errors for async or Promise-returning functions—even if those come via a throw statement in an async function.
As in Ayotunde Ajayi's answer, you can solve this by using await to convert your asynchronous error to appear synchronously, since await will unwrap a Promise failure back into a thrown exception:
// within an async function
try {
await errorTest()
}
catch(err) {
console.log("OUTSIDE ERROR!" + err)
}
But behind the scenes, it will appear exactly as you suggested in your question:
errorTest()
.then(val=> console.log(val))
.catch(err=> console.error("ERROR OCCURRED"))
You need to await errorTest
const callFunction=async()=>{
try{
const result = await errorTest()
}catch(err){
console.log(err)
}
}
callFunction ()
Note that the await errorTest() function has to also be in an async function. That's why I put it inside callFunction ()
Another Option
const errorTest = async() => {
try{
const result = await $.get("http://dataa.fixer.io/api/latest?access_key=9790286e305d82fbde77cc1948cf847c&format=1");
console.log(result)
}catch(err){
console.log(err)
}
}
I think the fundamental misunderstanding here is how the event loop works. Because javascript is single threaded and non-blocking, any asynchronous code is taken out of the normal flow of execution. So your code will call errorTest, and because the call to $.get performs a blocking operation (trying to make a network request) the runtime will skip errorTest (unless you await it, as the other answers have mentioned) and continue executing.
That means the runtime will immediately jump back up to your try/catch, consider no exceptions to have been thrown, and then continue executing statements which come after your try/catch (if any).
Once all your user code has ran and the call stack is empty, the event loop will check if there are any callbacks that need to be ran in the event queue (see diagram below). Chaining .then on your async code is equivalent to defining a callback. If the blocking operation to $.get completed successfully, it would have put your callback in the event queue with the result of errorTest() to be executed.
If, however, it didn't run successfully (it threw an exception), that exception would bubble up, as all exceptions do until they're caught. If you have defined a .catch, that would be a callback to handle the exception and that'll get placed on the event queue to run. If you did not, the exception bubbles up to the event loop itself and results in the error you saw (Uncaught (in promise) error) -- because the exception was never caught.
Remember, your try/catch has long since finished executing and that function doesn't exist anymore as far as the runtime is concerned, so it can't help you handle that exception.
Now if you add an await before errorTest() the runtime doesn't execute any of your other code until $.get completes. In that case your function is still around to catch the exception, which is why it works. But you can only call await in functions themselves that are prefixed with async, which is what the other commenters are indicating.
Diagram is from https://www.educative.io/answers/what-is-an-event-loop-in-javascript. Recommend you check it out as well as https://www.digitalocean.com/community/tutorials/understanding-the-event-loop-callbacks-promises-and-async-await-in-javascript to improve your understanding of these concepts.
Suppose I have an async function
static async update (id, data){
try {
//async function below
_DB.putsomedata()
return true
} catch(e){
//log errors
}
}
And although I don't need the result of _DB.putsomedata(), I still need to know if the update() function finished without errors.
I did some testing and noticed that the result will always return true (thats expected), but in case it fails, the the error is never caught in the catch block, and that raises an unhandled exception.
Can somebody explain the behaviour?
Assuming _DB.putsomedata is an async function, you need to await it. Otherwise its Promise will simply continue in the background, where it eventually fails and produces the error. Your code will have continued on ahead in the meantime and the try..catch block will have long been exited.
putsomedata function is asynchonious, so the return statment in compute just after marking putsomedata as computable (and not launch, as for synchronious function).
putsomedata return probably a promise, which will be resolved after, when cpu will be avaiable.
you can use .promise() .then() .catch() functions
employeeData.js
function getById(id) {
return dbPromise.one(); // using pg-promise
}
employeeService.js
function getInfoById(id) {
return employeeData.getXYZ(id); // purposefully calling a function that does not exist in the employeeData module
}
employeeApi.js // Express route function
const getInfoById = (req, res) {
employeeService.getInfoById(123)
.then(response => {
res.json(response);
})
.catch(err => {
res.json(err); // this is not being triggered
});
}
In the employeeService above I purposefully mis-typed the function name and I think it should throw an undefined error for calling a function getXYZ that does not exist in the employeeData.js. However, the catch block in employeeApi.js is not called.
Can you suggest what I might be missing here?
I think it should throw an undefined error for calling a function that does not exist
Yes, it does that. It throws an exception, it does not return a promise. As such, there is no promise object on which the then(…).catch(…) methods could be invoked.
However, the catch block is not called.
There is no catch block, it's just a method call - which doesn't happen because there's an exception. To catch it, you would need an actual try/catch block.
But that would look weird, and that's the reason why promise-returning functions should never throw. You could wrap the code with the mistake in a new Promise executor which would catch them, but the simpler choice is to use async/await syntax which guarantees to always return a promise (and reject it in case of an exception in the function body).
async function getInfoById {
return employeeData.getXYZ(123);
}
I have a nodeJS project where I wish to use asynchronous functions. Namely, I'm using the Q library.
I have a function called someFunction(), that I wish to return a promise. With the then -function, I can then check whether the promise was resolved or rejected like so:
someFunction()
.then(
function(results) {
console.log("Success!");
},
function (error) {
console.log("An error occurred, and I would wish to log it for example");
}
);
What I intuitively expect with the function above is, that the error function would catch all possible errors. So if some exception is raised inside the someFunction, I can rest assured, that the error function will be run (the second function after 'then'). But it seems this is not the case.
For example, let's say the someFunction would be defined as so:
function someFunction() {
var deferred = Q.defer();
throw new Error("Can't bar.");
deferred.resolve("success");
}
Now if I call the function someFunction() like done in the upper code block, it won't run the error function. Why is that? Isn't the partial point of the promise Q.deferred to catch errors? Why should I manually reject every error that happens? I know I could set the whole content of someFunction to try/catch clause, and then reject the deferred, but that feels so wrong! There must be a better way, and I know for sure some of you stackoverflowers know it!
With this information, I began to think about where the deferred.reject and deferred.resolve is even meant to be used? Is it even meant to catch exceptions? Should I really just go through all the error cases manually, and call the deferred.reject on them? I'm interested to hear how this should be handled professionally.
Q has specific function for success and error, so use:
deferred.reject("error");
intead of throwing an Exception.
Next thing is that someFunction must return promise to be used as You use it:
function someFunction() {
var deferred = Q.defer();
try{
//some Asynchronous code
deferred.resolve("success");
}catch(e){
deferred.reject(e.message);
}
return deffered.promise; //return promise to use then
}
Because Promises ain't magic. They don't somehow magically catch Errors. They catch them, because they wrap the calls to the callbacks in try..catch-blocks, to convert Errors into rejected Promises.
If you want an Error to be handled by the Promise-chain, well put the function-call into a promise-chain: Q.resolve().then(someFunction).then(...).
Now any synchronous Error occuring in someFunction can be handled in the following then's.
Btw: If you use Q.defer(), and you're not dealing with some callback-style API, you're doing it definitely wrong. Search for the Deferred-antipattern.
it won't run the error function. Why is that?
Because you synchronously threw an exception, instead of returning a promise. Which you never should.
Isn't the partial point of the promise Q.deferred to catch errors?
No. then and catch implicitly catch exceptions in their callbacks, defferreds don't - they're just a (deprecated) API to create promises.
Why should I manually reject every error that happens?
Because asynchronous errors are expected to be passed to callbacks anyway, instead of being thrown.
I know I could set the whole content of someFunction to try/catch clause, and then reject the deferred, but that feels so wrong! There must be a better way!
There is: the Q.Promise constructor, the standard (ES6) promise creation API. It has the benefit of being able to catch synchronous exceptions from the executor function:
function someFunction() {
return new Q.Promise(function(resolve) {
throw new Error("Can't bar.");
resolve("success");
});
}
throwing an error will stop the code from executing (and will close node) unless you catch the error in a try/catch block.
handled errors from requests can be passed to the .catch chain by using deferred.reject(error). code errors and custom thrown errors needs to be handled inside try/catch, which is the right way to handle such errors.
function someFunction() {
var deferred = Q.defer();
deferred.reject("Can't bar.");
// or
try {
throw new Error("Can't bar.");
}
catch(err) {
deferred.reject("Can't bar.");
}
deferred.resolve("success");
}