简体   繁体   English

如何在本机插件中创建node.js错误对象?

[英]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::Error::New()如何创建错误对象?

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

actually the api was changed. 实际上api已经改变了。 now, you can throw an exception in this way 现在,你可以用这种方式抛出异常

...
Isolate* isolate = args.GetIsolate();
isolate->ThrowException(Exception::TypeError(
    String::NewFromUtf8(isolate, "Your error message")));
...

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. 据我所知,没有v8::Error类,但是v8::Exception提供静态成员函数,通过提供v8::String参数来构造不同类型的错误。

Take a look at the v8::Exception Class Reference , that's probably what you're looking for. 看一下v8 :: Exception Class Reference ,这可能就是你要找的东西。

I hope this helps. 我希望这有帮助。

This is not specific to Node, you can just use the ThrowException method from the V8 API. 这不是特定于Node的,您可以使用V8 API中的ThrowException方法。 It requires one parameter of type Exception which you can create with one of the static methods on the Exception class. 它需要一个Exception类型的参数,您可以使用Exception类中的一个静态方法创建它。

There are examples on how to do it in this Node tutorial but feel free to check out my code on GitHub too. 有关如何在此Node教程中执行此操作的示例,但也可以 GitHub上查看我的代码

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

NOTE: Don't forget to return with Undefined() after calling ThrowException . 注意:在调用ThrowException之后,不要忘记返回Undefined() (Even scope.close is unnecessary in this case.) (在这种情况下,甚至不需要scope.close 。)

Further reading: 进一步阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM