Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle errors and return the callback without throwing #4

Closed
mapsam opened this issue Jun 17, 2016 · 2 comments
Closed

Handle errors and return the callback without throwing #4

mapsam opened this issue Jun 17, 2016 · 2 comments

Comments

@mapsam
Copy link
Contributor

mapsam commented Jun 17, 2016

In #3 we are beginning to add checks for proper parameters and throwing errors if they are unexpected types. Currently we use the following approach:

if (!info[2]->IsFunction()) 
{
    Nan::ThrowTypeError("third arg 'callback' must be a function");
    return;
}

In an asynchronous function, this throws instead of returning an error in the callback, which is a super big benefit of a callback function. To avoid this currently, we can wrap async functions in try/catch statements but that gets a bit clumsy.

How can we better handle errors in the .cpp & Nan side of things so they are returned as errors instead of thrown?

cc @springmeyer @GretaCB

@mapsam
Copy link
Contributor Author

mapsam commented Jun 22, 2016

Put together an elegant solution for this today with @springmeyer and @GretaCB. Instead of using Nan::ThrowTypeError() we can use Nan::MakeCallback. Here's the function for returning an error message as an error object to the callback:

function

inline void CallbackError(std::string message, v8::Local<v8::Function> callback) {
    v8::Local<v8::Value> argv[1] = { Nan::Error(message.c_str()) };
    Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, 1, argv);
}

usage:

CallbackError("this is my error message", callback);

Important note - right now callback is defined as a v8::Local<v8::Value> so we'll have to update that to a v8::Local<v8::Function> to comply with the function above.

@mapsam
Copy link
Contributor Author

mapsam commented Jun 22, 2016

Another important note - it's still useful to throw instead of return errors in some cases (i.e. callback function not provided) - so this type of error throwing will still exist for example purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant