How should I throw an error with a numeric code in NAN 1.x?

473 Views Asked by At

In NAN 1.9, the NanThrowError(const char *msg, const int errorNumber) method was deprecated, and it looks like an equivalent method is not present in NAN 2.0. Is there another way to get this same functionality with NAN, or is it just gone entirely?

2

There are 2 best solutions below

0
On BEST ANSWER

It was removed because it was unnecessary, easily implemented as needed.

inline v8::Local<v8::Value> makeErrorWithCode(const char *msg, int code) {
    NanEscapableScope();
    v8::Local<v8::Object> err = NanError(msg).As<v8::Object>();
    err->Set(NanNew("code"), NanNew<v8::Int32>(code));
    return NanEscapeScope(err);
}

return NanThrowError(makeErrorWithCode("message", 1337));
1
On

If you look at the version of nan.h linked in the question, you find that the deprecated method just creates a V8 exception and throws that:

NAN_DEPRECATED NAN_INLINE void NanThrowError(
  const char *msg
, const int errorNumber
) {
    NanThrowError(Nan::imp::E(msg, errorNumber));
}

namespace Nan { namespace imp {
    NAN_INLINE v8::Local<v8::Value> E(const char *msg, const int errorNumber) {
      NanEscapableScope();
      v8::Local<v8::Value> err = v8::Exception::Error(NanNew<v8::String>(msg));
      v8::Local<v8::Object> obj = err.As<v8::Object>();
      obj->Set(NanNew<v8::String>("code"), NanNew<v8::Int32>(errorNumber));
      return NanEscapeScope(err);
    }
  }  // end of namespace imp
}  // end of namespace Nan

I don't know why they introduced this change with no mention in the changelog on Github. There may be changes coming to the V8 engine that make it difficult to decide on a good default error object.

I think the best option for now is to write a method on your class that creates a new V8 exception based on a message and error code and call NanThrowError on that exception object. You can use the internal implementation above as a guide.