Making my own exceptions

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Making my own exceptions

Robert Norris
Hello,

I want to flag internal application errors by throwing exceptions. It
seems reasonable to me to create a "subclass" of the standard Error
object that is specific to my application.

How do I go about doing this, exactly? From looking at jsexn.c, it seems
that all the exception classes are simply copies of the same thing.

Since I can't get at the class definition directly, I tried this in my
startup code (without error checking and such)

----------
     JSClass *clasp;

     clasp = malloc(sizeof(JSClass));
     memset(clasp, 0, sizeof(JSClass));

     JS_GetProperty(cx, global, "Error", &rval);
     JS_CallFunctionValue(cx, global, rval, 0, NULL, &rval);
     memcpy(clasp, JS_GetClass(cx, JSVAL_TO_OBJECT(rval)),
            sizeof(JSClass));

     clasp->name = "AppError";

     obj = JS_NewObject(cx, clasp, NULL, NULL);
     JS_DefineProperty(cx, global, "AppError", OBJECT_TO_JSVAL(obj),
                       NULL, NULL, JSPROP_READONLY | JSPROP_PERMANENT);
----------

And then ran this code:

----------
try {
     throw new MyError();
}
catch(e) {
     print("Exception: " + e);
     print();
     for(i in e)
         print(i + ": " + e[i]);
}
----------

Which yields this:

----------
Exception: [object Object]

message:
fileName:
lineNumber: 0
stack: @:0
@exn.js:2

----------

So its close, but not quite right. I think I need to setup the prototype
  when I create the AppError object, but I'm not sure what to set it to.
I'm also not sure why the message isn't being set.

Besides, this method of creating a throwaway object just to get at its
class definition seems really clunky.

Also, is there a way to call a function as a constructor (ie emulate the
"new" operator) from C? I can see the code in jsexn.c that lets me get
away with doing a normal call to the Exception function, but obviously
that doesn't generalise. Or is the rationale that you do this for
exceptions, use the JS_New* calls for the other builtin objects, and
roll your own for custom classes?

Anything else I should know here?

Thanks,
Rob.
_______________________________________________
mozilla-jseng mailing list
[hidden email]
http://mail.mozilla.org/listinfo/mozilla-jseng
Reply | Threaded
Open this post in threaded view
|

Re: Making my own exceptions

Robert Norris
> try {
>     throw new MyError();
> }

> I'm also not sure why the message isn't being set.

My mistake of course. Giving the constructor an argument sets up the
message just nicely.

THe prototype stuff stands, however.

Rob.
_______________________________________________
mozilla-jseng mailing list
[hidden email]
http://mail.mozilla.org/listinfo/mozilla-jseng