diff --git a/napi-inl.h b/napi-inl.h index 98c578ed1..4232287f9 100644 --- a/napi-inl.h +++ b/napi-inl.h @@ -3370,9 +3370,30 @@ inline napi_value ObjectWrap::ConstructorCallbackWrapper( } T* instance; + auto handleConstructorException = [](const CallbackInfo& info) { + napi_status status = napi_remove_wrap(info.Env(), info.This(), nullptr); + NAPI_FATAL_IF_FAILED(status, + "ObjectWrap::ConstructorCallbackWrapper", + "Failed to remove wrap from failed ObjectWrap instance construction"); + }; napi_value wrapper = details::WrapCallback([&] { CallbackInfo callbackInfo(env, info); +#ifdef NAPI_CPP_EXCEPTIONS + try { + instance = new T(callbackInfo); + } catch (const Error& e) { + handleConstructorException(callbackInfo); + e.ThrowAsJavaScriptException(); + } +#else instance = new T(callbackInfo); + if (callbackInfo.Env().IsExceptionPending()) { + Error e = callbackInfo.Env().GetAndClearPendingException(); + handleConstructorException(callbackInfo); + e.ThrowAsJavaScriptException(); + delete instance; + } +# endif // NAPI_CPP_EXCEPTIONS return callbackInfo.This(); });