简体   繁体   中英

How can I log an error as if it was uncaught?

I have a complex JavaScript application where when certain unexpected errors occur, I want to log them for debugging but continue.

How do I log them to the console so that their stack is accessible in the normal fashion for an uncaught error?

A uncaught error in the Chrome console normally shows only the error message, and has a disclosure triangle which can be clicked to show the stack trace. This (and any other debugging features Chrome has now or might add in the future for uncaught errors) is what I want.

If I do the obvious catch (e) { console.log(e); } catch (e) { console.log(e); } or console.error(e) , the error object is instead shown in object-inspector fashion — there is a triangle but clicking it shows the properties of the error object (so I have to click four more times to get the stack property in a poorly-formatted way). I could log e.stack , but that's still missing some standard features.

setTimeout(function () { throw e; }, 0); is another option, but confuses debugging because it changes the ordering of messages in the console. (Putting the entire code-which-might-throw in a setTimeout might be feasible, but I want to investigate just fixing the logging first.)

console.log(prettyformatstack(e)); instead!

where prettyformatstack(e) takes an error returns the string you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM