I am not sure where this conversation ended up so I hope I am not repeating
already said stuff but you can always create constructors that inherits
from Error and set the name.

```javascript
function CustomError(message) {
  this.message = message || '';
}
CustomError.prototype = new Error;
CustomError.prototype.name = CustomError.name;
CustomError.prototype.constructor = CustomError;

// whenever you need
throw new CustomError;
```

That will be highlighted in most consoles as red **CustomError** instance
you can inspect to read the message.

Hope this helped anyhow.

Best Regards




On Wed, Jul 10, 2013 at 9:23 AM, Jonas Sicking <[email protected]> wrote:

> Hi all,
>
> What is the current expected way for an author to throw a custom
> errors? You obviously could do something like:
>
> throw { reason: "TimeoutError" };
> or
> throw "TimeoutError";
>
> However that makes it very hard for anyone receiving an exception to
> inspect what it is. I.e. you'd first have to check what type of value
> it is, i.e. if it's a string, something that's instanceof Error, or
> something with just custom properties.
>
> Instead you can do
>
> throw new Error;
>
> However, as I understand it, that doesn't let you pass
> machine-readable information in the error. You can only pass a message
> which is intended for human consumption. I.e. something like:
>
> throw new Error("operation took too long and timed out.");
>
> Yet another alternative is to do
>
> let e = new Error;
> e.name = "TimeoutError";
> throw e;
>
> This is a little bit more code than expected though.
>
> A shorter alternative that is somewhat compatible with Error is
>
> throw { name: "TimeoutError" };
>
> However this means that 'instanceof Error' returns false, which could
> mean that code is forced to check which properties are set.
>
> The reason I'm asking is that the DOM has invented a completely new
> interface, DOMError. This seems pretty heavy-handed and yet another
> instance of the DOM doing it in its own way rather than using existing
> ES functionality.
>
> I'd like for the DOM to mimic what we expect authors to do. It's just
> not obvious to me what authors are expected to do if they want to
> throw a machine readable error. I.e. one that allows code to catch the
> error and handle it.
>
> / Jonas
> _______________________________________________
> es-discuss mailing list
> [email protected]
> https://mail.mozilla.org/listinfo/es-discuss
>
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to