It is possible to return false with some message?
function test(){
if(5 > 6){
return false;
return 'message'
}
if()
if()
}
I know - above example does not works. I will use this function in different part of code, and if test function return false I would like to throw an error with message
You can return an object:
function test(){
if(5 > 6){
return {
result: false,
message: 'message'
}
}
....
}
You cannot use return twice, as the code will terminate after the first return statement and return the corresponding value, but what you can do is return an object like this with as many params as you want, and then use them as you like
function test() {
if (5 < 6) {
return { status: true, message: 'message' }
}
}
const { status, message } = test();
console.log(status, message);
function test() {
if (5 > 6) {
return false;
}
return true;
}
if (!test()) {
throw new Error('FALSE returned');
}
How about that? Or better in the context of your example (since you plan to re-use that function):
function test() {
if (5 > 6) {
throw new Error('5 is not greater than 6.'); // error message is relevant to this function
}
// do something else
}
try {
test();
} catch (e) {
throw new Error('test() threw error.'); // error message is relevant to wherever it's called
}
You can still access the original error message in e.message.