Is there a way in JavaScript to listen console events?

前端 未结 6 2366
悲&欢浪女
悲&欢浪女 2020-12-05 04:53

I\'m trying to write handler for uncaught exceptions and browser warnings in Javascript. All errors and warnings should be sent to server for later review.

Handled e

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 05:33

    More Succint Way:

    // this method will proxy your custom method with the original one
    function proxy(context, method, message) { 
      return function() {
        method.apply(context, [message].concat(Array.prototype.slice.apply(arguments)))
      }
    }
    
    // let's do the actual proxying over originals
    console.log = proxy(console, console.log, 'Log:')
    console.error = proxy(console, console.error, 'Error:')
    console.warn = proxy(console, console.warn, 'Warning:')
    
    // let's test
    console.log('im from console.log', 1, 2, 3);
    console.error('im from console.error', 1, 2, 3);
    console.warn('im from console.warn', 1, 2, 3);

提交回复
热议问题