I have a problem with capturing console errors with Sentry in Next.js app.
So problem is that, somewhere inside a library which we do not have access to, we have following error with WebSocket WebSocket is already in CLOSING or CLOSED state
It is clearly seemed in chrome debug panel
But not sent to a sentry initialized with this code in next.config.js
const withPlugins = require('next-compose-plugins');
const { withSentryConfig } = require('@sentry/nextjs');
const { CaptureConsole } = require('@sentry/integrations');
const nextConfig = {
assetPrefix: process.env.PUBLIC_URL || '',
reactStrictMode: true,
poweredByHeader: false,
future: {
webpack5: true,
},
}
const sentryOptions = {
silent: true,
environment: process.env.NODE_ENV,
integrations: [
new CaptureConsole({
levels: ['error'],
}),
],
errorHandler: (err, _invokeErr, compilation) => {
compilation.warnings.push('Sentry CLI Plugin: ' + err.message);
},
};
module.exports = withPlugins(
[
[(config) => withSentryConfig(config, sentryOptions), {}]
],
nextConfig,
);
And sentry.client.config.js
is
import * as Sentry from '@sentry/nextjs';
import { CaptureConsole } from '@sentry/integrations';
import { Integrations } from '@sentry/tracing';
Sentry.init({
dsn: '...',
attachStacktrace: true,
environment: process.env.NODE_ENV,
release: process.env.RELEASE,
sampleRate: 1,
tracesSampleRate: 0.2,
integrations: [
new Integrations.BrowserTracing({
beforeNavigate: (context) => ({
...context,
name: window.location.pathname,
}),
}),
new CaptureConsole({
levels: ['error'],
}),
],
});
Althought another console.error
messages successfully sends to Sentry.
Maybe that error just not printed with console.error
and handled in some lower level?
Then how we can log it?
Use this as a direction and not as a complete solve and its not straight forward , instead of relying on CaptureConsole
- can you not listen for socket.onclose
and use a Sentry.captureException(
to send the error payload?
To capture the socket exceptions
Get all open websockets
const sockets = [];
const nativeWebSocket = window.WebSocket;
window.WebSocket = function(...args){
const socket = new nativeWebSocket(...args);
sockets.push(socket);
return socket;
};
setTimeout(() => {
// or create a button which, when clicked, does something with the sockets
console.log(sockets);
}, 1000);
// via : https://stackoverflow.com/a/59916046/13749957
OR use wshook
https://github.com/skepticfx/wshook
Once this is achieved and you have all sockets in play, tag on to the onclose and send it to sentry
exampleSocket.onclose = function (event) {
Sentry.captureException(...args)
};