Error objects in W3C APIs

Boris Zbarsky bzbarsky at MIT.EDU
Tue Feb 4 06:28:27 PST 2014


On 2/4/14 4:27 AM, Jonas Sicking wrote:
> The advantage of A is that it follows the pattern of current JS
> errors. The disadvantage is that it clutters the global object with a
> lot of error constructor functions which doesn't really provide any
> value as far as I can tell.

Don't they allow easy creation of these new error types from script?

There is no nice way I can see, from script, to produce an instance of 
Error with .name set to something else.  You have to new Error() and 
then explicitly set .name on the resulting object or something.  So a 
typical pattern like:

   throw new FooError("xyz");

becomes:

   var err = new Error("xyz");
   err.name = "FooError";
   throw err;

> Such information is possible even using option B, but requires that
> properties are added on the error object instances, rather than as a
> getter on the prototype (which is the pattern used by other properties
> on Error subclasses).

Adding the properties on the instances via the constructor is still 
nicer, as above...

I guess pages could basically define their own error constructors if 
they wanted to.

-Boris


More information about the es-discuss mailing list