Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing an error object in javascript

When throwing an Error object in my promise chain, i attach a "details" property to it so that the handler can know what to do with it in the eventual catch block.

If logging is enabled, what i do in part of the chain is log the error and then rethrow it like so :

.somePartOfThePromiseChain
.catch(err => {
            console.log("ERROR");
            console.log(err.details);
            debugger;
            throw err;
          });

This works fine however, if i wanted to print the entire Error i dont get an object as expected but something that looks different like so :

Error: My error description here
    at API.js:105
    at <anonymous>

while i was expecting a collapsable object format as per usual in Chrome dev tools.

Im not sure why this happens as i essentially just want to print the Error object and view its members when debugging. This has nothing to do with me rethrowing the error as you can imagine.

Thanks a bunch.

like image 734
Return-1 Avatar asked Feb 01 '18 13:02

Return-1


People also ask

How do you print an object in JavaScript?

stringify() method is used to print the JavaScript object. JSON. stringify() Method: The JSON. stringify() method is used to allow to take a JavaScript object or Array and create a JSON string out of it.

How do you return an error in JavaScript?

To return errors from functions as promises, there are generally two ways to produce rejected promises: The reject function of your Promise library. Throwing an exception in a then callback or returning a rejected promise from it will reject the resulting promise.

Does JavaScript have an error object?

When an error occurs, JavaScript will normally stop and generate an error message. The technical term for this is: JavaScript will throw an exception (throw an error). JavaScript will actually create an Error object with two properties: name and message.

How do I find JavaScript errors?

Right-click anywhere in the webpage and then select Inspect. Or, press F12 . DevTools opens next to the webpage. In the top right of DevTools, the Open Console to view errors button displays an error about the webpage.


1 Answers

console.dir (MDN, Chrome devtools docs) does that on most consoles:

try {
  const e = new Error();
  e.details = "details go here";
  throw e;
} catch (ex) {
  console.dir(ex);
}
(Look in the real console.)
like image 162
T.J. Crowder Avatar answered Oct 03 '22 07:10

T.J. Crowder