8

When a JavaScript exception is caught in a snippet and the exception is output using console.log, it appears as an empty object.

Example:

try {
  let foo = null;
  foo.bar;
} catch(exception) {
  console.log(exception);
  console.log("As opposed to:")
  console.error(exception);
}

7
  • 1
    What should be the correct behavior to you? Error Objects have no enumerable properties, so JSON.stringify(ErrorInstance) will return "{}". Most browsers console seem to call a special toString method (including the call-stack as a second line) that is not specified anywhere (the available toString returning only ErrorInstance#ConstructorName: ErrorInstance#Message). Maybe that would be enough? (Would still require an if(object instanceof Error) which will likely slow down even more the stringification algo, for all logs...)
    – Kaiido
    Commented Jun 25, 2018 at 1:38
  • And actually the behavior I described above is only when logging the Error alone. When logged as part of an object structure they expose yet an other representation (more object like)
    – Kaiido
    Commented Jun 25, 2018 at 1:55
  • The correct behavior would be more in line with that exposed by a browser, however the current behavior of .error (which seems to be aware of the special toString) would be satisfactory. Commented Jun 25, 2018 at 3:24
  • What is your question? Commented May 26, 2021 at 15:21
  • @Henke A bug report is not a question. Commented May 26, 2021 at 20:28
  • OK. Thanks for clarifying. I was actually looking for some Meta guidance on whether printouts in a caught error / exception should be done with console.log() or with console.error()? Your post was the closest I could find. My own opinion is that console.error() is preferable. And as I understand this comment of yours, you agree with me? Commented May 27, 2021 at 10:41
  • 1
    @Henke it would depend on your use case. I believe It's probable that console.error() would suit the majority of use cases. Commented May 28, 2021 at 20:21

0

You must log in to answer this question.

Browse other questions tagged .