Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create node.js error object in native addon?

Tags:

c++

node.js

v8

I want to create an error object. But there is no v8::Error::New() How can I create an error object?

    v8::Handle< v8::Value > result = v8::Undefined();
    v8::Handle< v8::Value > error = v8::Undefined();

    if(m_errorMsg.empty())
    {
        // Not error
    }
    else
    {
        // HERE: Instead of a string I want an error object.
        error = v8::String::New( m_errorMsg.c_str() );
    }

    v8::Handle< v8::Value > argv[] = { error, result };

    m_callback->Call(v8::Context::GetCurrent()->Global(), 2, argv);
like image 815
aggsol Avatar asked Jan 13 '23 18:01

aggsol


2 Answers

actually the api was changed. now, you can throw an exception in this way

...
Isolate* isolate = args.GetIsolate();
isolate->ThrowException(Exception::TypeError(
    String::NewFromUtf8(isolate, "Your error message")));
...
like image 141
sarkiroka Avatar answered Jan 16 '23 02:01

sarkiroka


This is not specific to Node, you can just use the ThrowException method from the V8 API. It requires one parameter of type Exception which you can create with one of the static methods on the Exception class.

There are examples on how to do it in this Node tutorial but feel free to check out my code on GitHub too.

ThrowException(Exception::TypeError(String::New("This is an error, oh yes.")));
return Undefined();

NOTE: Don't forget to return with Undefined() after calling ThrowException. (Even scope.close is unnecessary in this case.)

Further reading:

  • documentation of the ThrowException method:
    http://bespin.cz/~ondras/html/namespacev8.html#a2469af0ac719d39f77f20cf68dd9200e
  • documentation of the Exception class:
    http://bespin.cz/~ondras/html/classv8_1_1Exception.html
like image 20
Venemo Avatar answered Jan 16 '23 00:01

Venemo