Skip to content

Commit

Permalink
Refactored throw_ex function
Browse files Browse the repository at this point in the history
- Added throw_ex function without exception_ctor parameter
- Refactored throw_ex function body to use v8::String::NewFromUtf8 to convert std::string function to v8::Local<v8::String> value. This makes the usage of windows.h obsolete.
  • Loading branch information
Roland Eischer authored and pmed committed Sep 15, 2018
1 parent a22d82a commit 6e6b519
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 23 deletions.
11 changes: 9 additions & 2 deletions v8pp/throw_ex.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,18 @@

namespace v8pp {

v8::Local<v8::Value> throw_ex(v8::Isolate* isolate, char const* str);

v8::Local<v8::Value> throw_ex(v8::Isolate* isolate, char const* str,
v8::Local<v8::Value> (*exception_ctor)(v8::Local<v8::String>) = v8::Exception::Error);
v8::Local<v8::Value> (*exception_ctor)(v8::Local<v8::String>));

inline v8::Local<v8::Value> throw_ex(v8::Isolate* isolate, std::string const& str)
{
return throw_ex(isolate, str.c_str());
}

inline v8::Local<v8::Value> throw_ex(v8::Isolate* isolate, std::string const& str,
v8::Local<v8::Value> (*exception_ctor)(v8::Local<v8::String>) = v8::Exception::Error)
v8::Local<v8::Value> (*exception_ctor)(v8::Local<v8::String>))
{
return throw_ex(isolate, str.c_str(), exception_ctor);
}
Expand Down
27 changes: 6 additions & 21 deletions v8pp/throw_ex.ipp
Original file line number Diff line number Diff line change
@@ -1,31 +1,16 @@
#include "v8pp/throw_ex.hpp"

#ifdef _WIN32
#include <windows.h>
#endif

namespace v8pp {

V8PP_IMPL v8::Local<v8::Value> throw_ex(v8::Isolate* isolate, char const* str)
{
return isolate->ThrowException(v8::String::NewFromUtf8(isolate, str));
}

V8PP_IMPL v8::Local<v8::Value> throw_ex(v8::Isolate* isolate, char const* str,
v8::Local<v8::Value> (*exception_ctor)(v8::Local<v8::String>))
{
v8::EscapableHandleScope scope(isolate);

v8::Local<v8::String> message;
#ifdef _WIN32
int const len = ::MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0);
if (len > 0)
{
std::vector<wchar_t> buf(len);
::MultiByteToWideChar(CP_ACP, 0, str, -1, &buf[0], len);
uint16_t const* data = reinterpret_cast<uint16_t const*>(&buf[0]);
message = v8::String::NewFromTwoByte(isolate, data,
v8::NewStringType::kNormal, len - 1).ToLocalChecked();
}
#else
message = v8::String::NewFromUtf8(isolate, str, v8::NewStringType::kNormal).ToLocalChecked();
#endif
return scope.Escape(isolate->ThrowException(exception_ctor(message)));
return isolate->ThrowException(exception_ctor(v8::String::NewFromUtf8(isolate, str)));
}

} // namespace v8pp

0 comments on commit 6e6b519

Please sign in to comment.