Is there a way in JavaScript to listen console events?

前端 未结 6 2392
悲&欢浪女
悲&欢浪女 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条回答
  •  Happy的楠姐
    2020-12-05 05:36

    You're going about this backwards. Instead of intercepting when an error is logged, trigger an event as part of the error handling mechanism and log it as one of the event listeners:

    try
    {
      //might throw an exception
      foo();
    }
    catch (e)
    {
      $(document).trigger('customerror', e);
    }
    
    function customErrorHandler(event, ex)
    {
      console.error(ex)
    }
    function customErrorHandler2(event, ex)
    {
      $.post(url, ex);
    }
    

    this code uses jQuery and is oversimplified strictly for use as an example.

提交回复
热议问题