Search code examples
javascriptgoogle-chromeconsole.logcustom-errors

Google Chrome shows custom error instance as pure object


I have reviewed how to create custom errors in JS, and wrote following code:

function AssertException(message)
{
  "use strict";
  Error.captureStackTrace(this, AssertException);
  Object.assign(this, {name: 'AssertException', message: message});
}
AssertException.prototype = Object.create(Error.prototype);
AssertException.prototype.name = 'AssertException'

Now, when I try to create instance and output it in console (in Chrome), it just shows it as object instead of error syntax (with stack in ellipsis block). See screenshot for details.

Is there way to define an error class that its output will be shown as for standard error classes (with stack in ellipsis)?

PS. console.log(new AssertException('abc').stack) shows expanded stack as string.

Google Chrome Version 50.0.2661.94 m

Console output screenshot for details


Solution

  • Although I do not have any code to prove the point, I believe the difference is to due to different "handlers" used by Chrome.

    The "Error" object and all its six subtypes are native objects. Therefore, for printing on console, Chrome uses a native handler. Perhaps, someone with more visibility to the chrome v8 source code can point to the exact handler.

    The "AssertException" object created by your code is non-native. Hence, the use of "Object Handler" to print its contents.

    FYI..you can check if a function is native or not using the following:

    https://gist.github.com/hilbix/a298f4c969593fabb08074628dc304b8