collecting log messages and show only if an error happns

There should be feature in javascript console API that shows log messages only if this run cycle ends with an error.

Let’s say

console.onErrorLog("something"); // not shown
console.onErrorLog("something else"); // still not shown
invalidFnCall(); // now it shows everything that has been kept in buffer

So, normal flow never shows these messages.

What is best way to achieve this behavior?