Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does "an empty MaybeLocal" mean?

Tags:

node.js

v8

I'm starting work with nodejs addons using Nan and am reading about MaybeLocal.

The docs say "If an API method returns a MaybeLocal<>, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a TerminateExecution exception was thrown. In that case, an empty MaybeLocal is returned."

Is this roughly the equivalent of returning a null pointer but with a simple class that can detect that?

like image 222
bmacnaughton Avatar asked Nov 04 '17 18:11

bmacnaughton


1 Answers

(V8 developer here.) Yes, an "empty MaybeLocal" is essentially a pointer that can be nullptr and forces the code to check for that case.

The background is that due to the nature of JavaScript, many of V8's API operations can (somewhat unexpectedly) fail: any time any JavaScript is executed, that JavaScript code might throw an exception. Even reading an object property could invoke a getter. We have learned from experience that it is exceedingly difficult to write client code that correctly checks for all these, so nowadays V8's API is mostly based on MaybeLocals that help you find all the places that need nullptr checks -- or .IsEmpty() checks, as they're called in the MaybeLocal world.

In cases where you can guarantee that a MaybeLocal cannot be empty, you can use .ToLocalChecked(), which will crash if the MaybeLocal was empty. Otherwise, a common pattern is:

Local<Value> value;
if (maybe_value.ToLocal(&value)) {
   // Do stuff with {value}.
} else {
   // Handle error. If you have a TryCatch, it should
   // have caught an exception.
}
like image 148
jmrk Avatar answered Nov 05 '22 10:11

jmrk