Subj : Re: How do I raise an exception? To : netscape.public.mozilla.jseng From : Thomas Sondergaard Date : Wed Aug 03 2005 02:30 pm Brendan Eich wrote: > If you want to make an instance of Error and throw it, you'll have to > get the value of the "Error" property of a properly initialized or > otherwise (lazy standard class resolution) configured global object, and > save it with a rooted pointer or jsval. > > Then you can call this Error constructor function object reference with > the JS_CallFunctionValue API, to create the exception object you wish to > throw, passing appropriate arguments. If that all works, set the new > exception object reference as the pending exception and return false. > > /be Does this look reasonable? I found it here: http://egachine.berlios.de/embedding-sm-best-practice/ar01s05.html#error-reporting inline JSBool ejs_throw_error(JSContext* cx, JSObject* obj, const char* msg) { JSString* jsstr; // if we get errors during error reporting we report those if ( ((jsstr=JS_NewStringCopyZ(cx, msg))) && (JS_AddNamedRoot(cx,&jsstr,"jsstr")) ) { jsval dummy; // We can't use JS_EvaluateScript since the stack would be wrong JSFunction *func; JSObject* fobj; const char* fbody="throw new Error(msg);"; const char* argnames[]={"msg"}; if ((func=JS_CompileFunction(cx, obj, NULL, 1, argnames, fbody, strlen(fbody), NULL, 0))) { // root function if ( ((fobj = JS_GetFunctionObject(func))) && (JS_AddNamedRoot(cx, &fobj, "fobj")) ) { jsval args[]={STRING_TO_JSVAL(jsstr)}; JS_CallFunction(cx, obj, func, 1, args, &dummy); JS_RemoveRoot(cx, &fobj); } } JS_RemoveRoot(cx,&jsstr); } return JS_FALSE; } .