nodejs / node-addon-api

Module for using Node-API from C++
MIT License
2.1k stars 457 forks source link

Throwing an object as an exception? #1460

Closed erikjalevik closed 4 months ago

erikjalevik commented 4 months ago

I'd like to add an error code to exceptions thrown from C++ into JavaScript. Is it possible? All the documented APIs just take a string.

I tried:

  Napi::Error err = Napi::TypeError::New(env, errorMessage);
  err.Set("code", Napi::Number::New(env, 123));
  err.ThrowAsJavaScriptException();

But the code property is not present on the error object received in JavaScript land.

KevinEady commented 4 months ago

Hi @erikjalevik ,

This should be supported. I created a small test and this passes:

void ThrowTypeErrorWithMessageLength(const CallbackInfo& info) {
  auto env = info.Env();
  std::string message = info[0].As<String>().Utf8Value();
  auto err = TypeError::New(env, message);
  err.Set("messageLength", Number::New(env, message.length()));
  err.ThrowAsJavaScriptException(); // or throw err;
}

When I call this function with a parameter of "test", I get the messageLength property on the error thrown, or formally:

err instanceof TypeError && err.message === 'test' && err.messageLength === err.message.length

Could you provide some more code to reproduce your issue...?

erikjalevik commented 4 months ago

Apologies, my bad. I had mixed up the code paths for exception throwing and returning errors as part of a Node callback. Sorry to waste your time!

tuler commented 3 months ago

Is there any example on how to subclass Error or TypeError?