0

JavaScript, when throw-ing a built-in error as such:

throw new Error("Something was wrong");

displays the text nicely - you can't tell you threw an object enter image description here

However, when creating a custom error by subclassing the Error object (or other error object for that matter), the thrown error is not displayed the same way in the console.

So, by using this code:

var ImproperlyConfigured = function(message){
    this.name ="ImproperlyConfigured";
    this.message = message || "The object you tried to construct was improperly configured due to an unknown error";
}
ImproperlyConfigured.prototype = new Error();

The following is the output enter image description here

I don't like the fact that the object properties (name and message) are shown. In fact, I don't like that I don't understand why the properties are shown.

I've googled a bit and I got the feeling that by implementing a toString method will help but, by using this method, the fact that the name of the error is no longer in red puzzles me even more.

Code

var ImproperlyConfigured = function(message){
    this.name ="ImproperlyConfigured";
    this.message = message || "The object you tried to construct was improperly configured due to an unknown error";
    this.toString = function(){
        return this.message;
    }
}
ImproperlyConfigured.prototype = new Error();

Output: enter image description here

What I would like to achieve is a standard looking error, by the use of custom error and, of course, by not using the console.error method manually in a try...catch block.

Is this possible?

Community
  • 1
  • 1
Adelin
  • 7,809
  • 5
  • 37
  • 65
  • I just tried your code in Chromium and [the output was fine](http://i.imgur.com/TPVpkHB.png). In what software/console were you testing ? – Denys Séguret Apr 16 '16 at 13:27
  • 1
    Developer consoles don't follow any particular standard, and they pretty much do what they want. – Pointy Apr 16 '16 at 13:28
  • @DenysSéguret I'm currently using [Google Chrome](https://www.google.com/chrome/browser/desktop/) Version 49.0.2623.110 m – Adelin Apr 16 '16 at 13:53
  • @Pointy - Can you post that as an answer? I wrongly assumed we can control how an error looks in the console from JavaScript, but this issue has nothing to do with JS. – Adelin May 03 '16 at 09:49

1 Answers1

0

As Pointy correctly pointed out (pun intended), the issue here is not with JavaScript, but rather with the environment JavaScript is running (in this case, Google Chrome).

In another environment (like Chromium, Firefox, NodeJS, etc.) the behavior will likely be different, using the same code, depending on how those JavaScript hosts are handling these cases.

Adelin
  • 7,809
  • 5
  • 37
  • 65