Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you both throw an Error and return a value from a Javascript function

Tags:

javascript

What is the cleanest way to both throw an error and return a value from a Javascript function?

Here's one proposed approach as a starting point:

(e, v) => {
   setTimeout(() => { throw(e) }, 0);
   return v; 
}

Here's a runnable snippet to demonstrate further:

var val = ((e, v) => {
   setTimeout(() => { throw(e) }, 0); // will throw in console
   return v; 
})('errMSG', 1)


alert(val); // 1 
like image 562
hally9k Avatar asked Oct 30 '25 01:10

hally9k


1 Answers

Return an object that contains the value you are interested in, and an error:

return {
    value: "foo",
    error: new Error("bar")
}

The receiver can then throw the error as necessary

like image 137
Dexygen Avatar answered Oct 31 '25 16:10

Dexygen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!