How to throw out of then-catch block? - javascript

I am currently figuring out how to throw an Exception out of a then catch block. I want to get into the catch that is inside the errorHandler() function.
const errorHandler = function () {
try {
thisFunctionReturnsAnError().then(response => {
console.log(response);
});
} catch (e) {
console.log(e); //How to trigger this?
}
};
const thisFunctionReturnsAnError = function () {
return3()
.then(value => {
throw new Error('This is the error message.');
})
.catch(err => {
//return Promise.reject('this will get rejected');
throw err;
//this one should somehow got to the catch that is located in the errorHandler() function. How to do this?
//I know that this 'err' will be in the next catch block that is written here. This is not what i want.
});
};
const return3 = async function () {
return 3;
};
errorHandler();
I searched a while on stackoverflow but nothing helped me. I am sure that this question got asked often but I could not find the answer, sorry for that.
EDIT:
added here another version of the code but it still does not work
const errorHandler = async function () {
try {
thisFunctionReturnsAnError()
.then(response => console.log(response))
.catch(err => console.log(err));
} catch (e) {
//console.log(e); //How to trigger this?
}
};
const thisFunctionReturnsAnError = function () {
return3()
.then(value => {
throw new Error('This is the error message.');
})
.catch(err => {
return Promise.reject(`Message is: ${err}`);
});
};
const return3 = async function () {
return 3;
};
errorHandler();
I will get the following error message:
Uncaught (in promise) Message is: Error: This is the error message.

Your code can't be executed, because "thisFunctionReturnsAnError" is not returning an Promise. That means that you can't call "then" on the return value.
thisFunctionReturnsAnError().then(response => { // will not work
Why not always use a promise?
const errorHandler = function () {
thisFunctionReturnsAnError()
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log('errorHandler: Handle the error.');
});
};
const thisFunctionReturnsAnError = function () {
return return_Three()
.then((value) => {
throw new Error('This is the error message.');
})
.catch((err) => {
//return Promise.reject('this will get rejected');
throw err;
//this one should somehow got to the catch that is located in the errorHandler() function. How to do this?
//I know that this 'err' will be in the next catch block that is written here. This is not what i want.
});
};
const return_Three = async function () {
return 3;
};
errorHandler();
/*****JUST ANOTHER SYNTAX*******/
const secondErrorHandler = async function () {
try {
await thisFunctionReturnsAnError();
} catch (error) {
console.log('secondErrorHandler: Handle the error.');
}
};
secondErrorHandler();

You cannot handle promise rejections with synchronous try/catch. Don't use it, use the promise .catch() method like in your thisFunctionReturnsAnError function.
You can handle promise rejections with try/catch when using async/await syntax (which you already do, albeit unnecessarily, in return3):
async function errorHandler() { /*
^^^^^ */
try {
const response = await thisFunctionReturnsAnError();
// ^^^^^
console.log(response);
} catch (e) {
console.log(e); // works
}
}

Related

escape loop using an error from async function?

let me explain what I mean using an example
async function async_function(){
await new Promise(r=>setTimeout(r,3000));
throw 'task completed'
}
async function do_something_meanwhile() {
await new Promise(r => setTimeout(r, 500));
console.log(Math.floor(Math.random()*10));
}
(async ()=>{
try {
async_function(); //this returns an error after a while
while (...)
await do_something_meanwhile();
} catch (err) { console.log('exited with error:',err) }
console.log('moving on');
})();
I'm trying to run an async function and after it is complete immediately terminate the loop,
the best way I could think of (without any time delay) was to send an error
but it gives this error instead of moving on after it's done:
node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: 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(). The promise rejected with the reason "task
completed".] {
code: 'ERR_UNHANDLED_REJECTION'
}
is there a way around this or a better to achieve the desired effect?
You can handle rejection by setting an error variable that you can check in the loop:
try {
let error;
async_function()
.catch(err => error = err);
while (...) {
if (error) {
throw error;
}
await do_something_meanwhile();
}
} catch (err) {
console.log('exited with error:',err)
}
If you need to proactively tell do_something_meanwhile to terminate as well, you could use an AbortController and pass its signal to do_something_meanwhile.
try {
let error;
const controller = new AbortController();
const { signal } = controller;
async_function()
.catch(err => {
error = err;
controller.abort();
});
while (...) {
if (error) {
throw error;
}
await do_something_meanwhile(signal);
}
} catch (err) {
console.log('exited with error:',err)
}
I think if I were doing that, I might subclass AbortController so I can put the error in it:
class AbortContollerWithError extends AbortController {
abort(error) {
this.error = error;
super.abort();
}
}
then:
try {
const controller = new AbortController();
const { signal } = controller;
async_function()
.catch(err => {
controller.abort(err);
});
while (...) {
if (signal.aborted) {
throw controller.error;
}
await do_something_meanwhile(signal);
}
} catch (err) {
console.log('exited with error:',err)
}
...or something along those lines.
You asked how you'd use the signal in do_something_meanwhile, and suggested in a comment that you're really using a timer in it. That's where the signal's abort event comes in handy, you can use that to settle the promise early:
async function do_something_meanwhile(signal) {
let cancelError = {};
try {
await new Promise((resolve, reject) => {
const timer = setTimeout(resolve, 500);
signal.addEventListener("abort", () => {
clearTimeout(timer);
cancelError = new Error();
reject(cancelError);
});
});
console.log(Math.floor(Math.random() * 10));
} catch (error) {
if (error === cancelError) {
// Probably do nothing
} else {
// Something else went wrong, re-throw
throw error;
}
}
}
Promise.all can run async_function and do_something_meanwhile in parallel mode.
While Promise/A doesn't have a cancel method, you can define a stopFlag, and check it in do_something_meanwhile function and the while loop.
let stopFlag = false
async function async_function() {
await new Promise(r=>setTimeout(r, 3000));
throw 'task completed'
}
async function do_something_meanwhile() {
await new Promise(r => setTimeout(r, 500));
if (!stopFlag) {
console.log(Math.floor(Math.random() * 10));
}
}
(async()=>{
try {
await Promise.all([
async_function().catch((err) => {
stopFlag = true
throw err
}), // this returns an error after a while
(async () => {
while (!stopFlag)
await do_something_meanwhile();
})()
])
} catch (err) {
console.log('exited with error:', err)
}
console.log('moving on');
})();

NodeJS use errors for specific cases

Im using the following function that works ok, However I have some issue with the error handling
e.g.
I want to catch generic error for all the functions
If fn1 or fn2 returns any error the function should throw 'generic error occurred`
Here is the what I need
if getData2 doesn’t have specific property value (see the if) return a uniq error uniq error occurred and not the general error...
This is working example
https://jsfiddle.net/8duz7n23/
async function func1() {
try {
const data = await getData1()
console.log(data)
const data2 = await getData2();
if (!data2.url === !"https://test2.com") {
throw new Error("uniq error occurred ")
}
return data2.url
} catch (e) {
throw new Error("generic error occurred ")
}
}
async function getData1() {
return "something"
}
async function getData2() {
return {
url: "http://test.com"
}
}
func1().then(result => {
console.log(result);
}).catch(error => {
console.log(error);
});
Now If I throw the uniq error the catch will throw the general error.
I want that in case func2 will have some error it still throw away
a general error but just if doenst have the right url,
trow all the way up the uniq error ...
Is there any cleaner way to do it in nodejs?
I dont want to use an if statement for messages in the catch etc...
I want that the will thrown to the upper level function and not to the catch
In order to propagate error to the "upper level", you should have to throw it again in catch block.
You can add your custom error type and check if the error is what you're looking for or not.
class UrlMismatchError extends Error {
name="UrlMismatchError"
}
async function func1() {
try {
const data = await getData1()
console.log(data)
const data2 = await getData2();
if (data2.url !== "https://test2.com") {
throw new UrlMismatchError("uniq error occured");
}
return data2.url
} catch (e) {
if (e instanceof UrlMismatchError) {
throw e;
} else {
// handle generic errors
throw new Error("generic error occured");
}
}
}
async function getData1() {
return "something"
}
async function getData2() {
return {
url: "http://test.com"
}
}
func1().then(result => {
console.log(result);
}).catch(error => {
console.error(error.message);
});
I dont want to use an if statement for messages in the catch etc...
I want that the will thrown to the upper level function and not to the catch
No you cannot do that, because javascript is not java, so you cannot do such thing as the follows:
// the code snippet below wont work
try {
doSomething();
} catch(UrlMismatchError e) {
// propagate error to the upper level
throw e;
} catch(Error e) {
// handle all the other errors
console.log(e);
}

Confusion around 'nested' try/catch statements in Javascript

Essentially I have an async function containing a try/catch that calls another async function also containing a try catch, and I'm getting a bit confused about how to properly implement what I'm doing. Some "pseudocode" showing my current implementation:
const main = async () => {
try {
const test = await secondFunc();
console.log(test);
} catch(err) {
console.log('Found an error!');
console.log(err);
}
const secondFunc = async () => {
try {
await performSomeRequestExample();
} catch(err) {
if (err.x === 'x') {
doSomething();
} else {
//********
throw err;
//********
}
}
So what I'm trying to do is get the throw(err) (surrounded by the asterisks) to be caught by the catch in main() which will also call the console.log('Found an error!'), but what currently happens is the error is thrown from secondFunc(), the catch in main() is never hit and I get an unhandled promise rejection.
Any guidance on what I'm doing wrong?
My advice is to minimize using try/catch unless absolutely necessary. With async functions (or any functions that return a Promise object) you can usually simplify things by not worrying about try/catch blocks unless you need to do something specific with certain errors. You can also use .catch rather than try/catch blocks to make things easier to read.
For example your code above could be written like this:
const main = async () => {
const test = await secondFunc().catch(err => {
console.log("Found an error from secondFunc!", err);
throw err; // if you want to send it along to main's caller
});
if (test) {
console.log("Test", test);
}
};
const secondFunc = () => {
return performSomeRequestExample().catch(err => {
if (err.x === "x") {
doSomething();
} else {
throw err;
}
});
};
const performSomeRequestExample = () => Promise.reject("bad");
main().then(
() => console.log("worked"),
err => console.log("failed from main", err)
);
In secondFunc we don't need to use async since we can just return the promise coming back from performSomeRequestExample and handle any failures in the .catch.
You should use
const secondFunc = async () => {
performSomeRequestExample().then(res =>{
console.log(res);
})
.catch(err => {
console.log(err);
}
)
Add a return before the await of performSomeRequestExample.
const secondFunc = async () => {
try {
return await performSomeRequestExample();
} catch (err) {
if (err.x === 'x') {
console.log('x');
} else {
throw err;
}
}
}
or you can also use .catch() after the awaited function.
Another solution can be like this
const main = async() => {
try {
const test = await secondFunc();
console.log(test);
} catch(err) {
console.log('Found an error!');
console.log(err);
}
}
const secondFunc = async () => {
//return await performSomeRequestExample(); //for success
return await performSomeRequestExample(2); //for error
}
const performSomeRequestExample = async(abc=1) => {
return new Promise(function(resolve,reject){
if(abc ==1){
setInterval(resolve("yes"),400);
}else{
setInterval(reject("opps"),400);
}
});
}
main();
Test this code at this link:
https://repl.it/repls/JoyfulSomberTelevision

Node.js / MongoDB: can't catch error from Cursor.map callback outside of this callback

mongodb 3.6.3
node 8.10.0
I discovered this accidentally and after some time researching problem still can't figure it out. My code has global error handler that should catch all errors, but error that originated from find().map callback was skipped by it and process was exited with standard error log to console.
Here is test code that i come up with
(async () => {
const {MongoClient} = require('mongodb');
const uri = 'your uri';
const connection = MongoClient.connect(uri, {useNewUrlParser: true});
connection.catch((e) => {
console.log('inside connection.catch');
console.log(e);
});
const collection = (await connection).db().collection('collection');
const findPromise = collection.find({}).limit(0).skip(0);
const functionWithError = (item) => {
throw new Error('functionWithError');
};
// This fails to catch error and exits process
// try {
// const items = await findPromise.map(functionWithError).toArray().catch((e) => console.log('Promise catch 1'));
// console.log(items);
// } catch (e) {
// console.log('map error 1');
// console.log(e);
// }
// This (obviously) works and 'inside map error' is written to console
try {
const items = await findPromise.map(() => {
try {
functionWithError();
} catch (e) {
console.log('inside map error'); // this will be outputted
}
}).toArray().catch((e) => console.log('Promise catch 2'));
console.log(items);
} catch (e) {
console.log('map error 2');
console.log(e);
}
})();
I don't see any problem in code and expect 'Promise catch 1' or 'map error 1' to be logged to console. So whats the problem? Thanks in advance.
Its about the scope of asynchronous function. If you try to use asynchronous function in try..catch block, asynchronous function goes out of scope of try..catch block, so it, it is always good practice to return errors in asynchronous function callback, which can be handled by simple if..else check.
Useful link
Example1: throwing an error in async-await, where no asynchronous process is running.
(async () => {
const someAsync = async () => {
throw new Error('error here');
};
try {
await someAsync();
} catch (e) {
console.log('error cached as expected!');
}
console.log('execution continues');
})();
Example2: throwing an error in async-await, where the asynchronous process is running.
(async () => {
const someAsync = async () => {
let timeInMS = 0; // 0 milliseconds
let timer = setTimeout(function() {
clearTimeout(timer);
throw new Error('error here');
}, timeInMS);
};
try {
await someAsync();
} catch (e) {
console.log('error cached as expected!');
}
console.log('execution continues');
})();

How to resolve promises and catch an error

I am trying to user webgazer.js where my code basically checks to see whether the webgazer is initialized and when it is initialized it resolves a promise which dispatches an action. This works however if for example there is no webcam I need to throw an error. The error in my code never gets called.
Here is my code
export function detectJsCamera() {
return async(dispatch) => {
dispatch({type: types.JS_DETECTING_CAMERA});
try {
await detectCamera();
await dispatch({type: types.JS_CAMERA_DETECTED});
} catch (error) {
await dispatch({type: types.CAMERA_DETECTION_FAILED, error: error.message});
throw error;
// this.props.history.push('/setup/positioning')
};
}
}
const detectCamera = () => new Promise((resolve, reject) => {
const checkIfReady = () => {
if (webgazer.isReady()) {
resolve('success');
} else {
console.log('called')
setTimeout(checkIfReady, 100);
}
}
setTimeout(checkIfReady,100);
});
You will need to reject in order to throw an exception like below
const detectCamera = () => new Promise((resolve, reject) => {
const checkIfReady = () => {
if (webgazer.isReady()) {
resolve('success');
} else {
console.log('called');
reject("some error");
}
}
setTimeout(checkIfReady,100);
});
You need to call reject() in your detectCamera method when your webgazer is not initialised then it would be caught in your catch block in detectJsCamera method.

Categories