aggsol
aggsol

Reputation: 2490

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

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);

Upvotes: 4

Views: 2051

Answers (3)

sarkiroka
sarkiroka

Reputation: 1542

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")));
...

Upvotes: 5

Venemo
Venemo

Reputation: 19097

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:

Upvotes: 2

GabrielaTz
GabrielaTz

Reputation: 116

As far as i know there isn't a v8::Error class but there's the v8::Exception that provides static member functions to construct different types of errors by supplying a v8::String argument.

Take a look at the v8::Exception Class Reference, that's probably what you're looking for.

I hope this helps.

Upvotes: 2

Related Questions