Как сообщить о console.error с помощью Sentry? - PullRequest
0 голосов
/ 01 июня 2018

У меня есть приложение, в котором сообщается о некоторых критических проблемах с console.error, но не thrown, поэтому приложение может продолжать работать - возможно, в поврежденном состоянии.

Необходимо также сообщить о console.error проблемах,но библиотека Sentry (Raven) отправляет на сервер только сгенерированные исключения.

Кто-нибудь знает, как решить эту проблему?

(в идеале без необходимости переписывать все вызовы console.error, причинатакже некоторые библиотеки поставщиков могут по-прежнему записывать вывод только в консоль)

Ответы [ 3 ]

0 голосов
/ 08 ноября 2018

Вот более надежное решение для переопределения

// creating function declarations for better stacktraces (otherwise they'd be anonymous function expressions)
var oldConsoleError = console.error;
console.error = reportingConsoleError; // defined via function hoisting
function reportingConsoleError() {
  var args = Array.prototype.slice.call(arguments);
  Sentry.captureException(reduceConsoleArgs(args), { level: 'error' });
  return oldConsoleError.apply(console, args);
};

var oldConsoleWarn = console.warn;
console.warn = reportingConsoleWarn; // defined via function hoisting
function reportingConsoleWarn() {
  var args = Array.prototype.slice.call(arguments);
  Sentry.captureMessage(reduceConsoleArgs(args), { level: 'warning' });
  return oldConsoleWarn.apply(console, args);
}

function reduceConsoleArgs(args) {
  let errorMsg = args[0];
  // Make sure errorMsg is either an error or string.
  // It's therefore best to pass in new Error('msg') instead of just 'msg' since
  // that'll give you a stack trace leading up to the creation of that new Error
  // whereas if you just pass in a plain string 'msg', the stack trace will include
  // reportingConsoleError and reportingConsoleCall
  if (!(errorMsg instanceof Error)) {
    // stringify all args as a new Error (which creates a stack trace)
    errorMsg = new Error(
      args.reduce(function(accumulator, currentValue) {
        return accumulator.toString() + ' ' + currentValue.toString();
      }, '')
    );
  }
  return errorMsg;
}
0 голосов
/ 24 июня 2019

Как пользователь @ kumar303 упомянул в своем комментарии к вопросу ... вы можете использовать интеграцию с консолью JS Sentry.Integrations.CaptureConsole.

См. https://docs.sentry.io/platforms/javascript/?platform=browsernpm#captureconsole для документации.

В конце ваш JS-код для настройки Sentry выглядит следующим образом:

Sentry.init({
  dsn: 'https://your-sentry-server-dsn',
  integrations: [
    new Integrations.CaptureConsole({
      levels: ['error']
    })
  ],
  release: '1.0.0',
  environment: 'prod',
  maxBreadcrumbs: 50
})

Если затем кто-то позвонит console.error, новое событие будет отправлено часовому.

0 голосов
/ 08 июня 2018

Нашел маленькое хакерское решение:

const consoleError = console.error;
console.error = function(firstParam) {
  const response = consoleError.apply(console, arguments);
  Raven.captureException(firstParam, { level: 'error' });
  return response;
};

Он просто оборачивает console.error и сообщает каждый из журналов ошибок в консоли Raven (Sentry).

Если у кого-то естьболее приятный подход (возможно, некоторая скрытая особенность Sentry), пожалуйста, не стесняйтесь поделиться!

...