Search code examples
reactjssentry

Is there anyway to push javascript console logs to sentry


I am using the console.error() console.warn() in man places in my app to track failing code. Is there anyway to automatically log these to Sentry. https://sentry.io.

It is a react app, and it seems the componentDidCatch() method they suggest only catches exceptions.


Solution

  • One way of doing this is to overwrite the console.error and console.warn with your own custom implementation, so whenever any part of the code calls the console.error or console.warn the call will be intercepted by your custom function where you can perform the required action on it.

    Following example shows a custom implementation of console.error method.

    //Store the original reference of console.error
    var orgError = console.error;
    //Overwirte the default function
    console.error = function(error) {
      //All error will be intercepted here
      alert("Intercepted -> " + error);
      //Invoke the original console.error to show the message in console
      return orgError(error);
    }
    try {
      //Following line will throw error
      nonExistentFunction();
    } catch (error) {
      console.error(error);
    }