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?
(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 MaybeLocal
s 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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With