Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import { getApolloApplyMiddlewareOptions, getApolloServerOptions } from './settings';
import { getSetting } from '../../modules/settings.js';
import { formatError } from 'apollo-errors';
//import timber from 'timber';
const timberApiKey = getSetting('timber.apiKey');
const sentryUrl = getSetting('sentry.url');
const sentryEnvironment = getSetting('sentry.environment');
const sentryRelease = getSetting('sentry.release');
import Sentry from '@sentry/node';
if (sentryUrl) {
Sentry.init({ dsn: sentryUrl, environment: sentryEnvironment, release: sentryRelease });
} else {
// eslint-disable-next-line no-console
console.warn("Sentry is not configured. To activate error reporting, please set the sentry.url variable in your settings file.");
}
export const setupGraphQLMiddlewares = (apolloServer, config, apolloApplyMiddlewareOptions) => {
// IMPORTANT: order matters !
// 1 - Add request parsing middleware
// 2 - Add apollo specific middlewares
// 3 - CLOSE CONNEXION (otherwise the endpoint hungs)
// 4 - ONLY THEN you can start adding other middlewares (graphql voyager etc.)
// WebApp.connectHandlers is a connect server
// you can add middlware as usual when using Express/Connect
// parse cookies and assign req.universalCookies object
Logger.prototype[level.toLowerCase()] = (message) => {
const simple = fmt(level, process.env.SCOPE || 'BOT', message);
if ((Object.keys(levels).indexOf(level) >= Object.keys(levels)
.indexOf(l.logLevel)) && Object.keys(levels).indexOf(level) < 3) {
// eslint-disable-next-line no-console
console.log(simple);
}
if (level.toLowerCase() === 'fatal' && Sentry) {
Sentry.captureMessage(message, {
level: 'fatal',
});
process.exit(4);
}
if (level.toLowerCase() === 'error') {
// eslint-disable-next-line no-console
console.error(simple);
if (typeof message === 'object') {
// eslint-disable-next-line no-console
console.error(message);
}
if (Sentry) {
Sentry.captureException(message);
}
}
};
}
});
const [command, ...subCommands] = input;
const options = {};
// Parse commands
for (let i = 0; i < subCommands.length; i += 1) {
options[subCommands[i]] = subCommands[i];
}
if (flags.report) {
console.clear();
console.log(chalk`{yellow {bold ERROR REPORTING}}`);
console.log();
const event_id = Sentry.captureMessage(`MESSAGE ${randomString(6)}`, Sentry.Severity.Info);
await SentryAPIClient.shared.userFeedBack(null, event_id);
process.exit(0);
}
if (flags.quiet) {
const emptyFunction = () => null;
console.log = console.info = emptyFunction;
if (spinner.fail) {
spinner.fail = emptyFunction;
}
if (spinner.start) {
spinner.start = emptyFunction;
}
maxBreadcrumbs: 50,
attachStacktrace: true,
}
// When we're developing locally
if (process.env.NODE_ENV !== 'production') {
/* eslint-disable-next-line global-require */
const sentryTestkit = require('sentry-testkit')
const { sentryTransport } = sentryTestkit()
// Don't actually send the errors to Sentry
sentryOptions.transport = sentryTransport
// Instead, dump the errors to the console
sentryOptions.integrations = [
new Sentry.Integrations.Debug({
// Trigger DevTools debugger instead of using console.log
debugger: false,
}),
]
}
Sentry.init(sentryOptions)
return {
Sentry,
captureException: (err, { req, res, errorInfo, query, pathname }) => {
Sentry.configureScope(scope => {
if (err.message) {
// De-duplication currently doesn't work correctly for SSR / browser errors
// so we force deduplication by error message if it is present
scope.setFingerprint([err.message])
const configureSentryRequestHandler = (app) => {
if (env !== 'development' && config.sentry.dsn) {
Sentry.init({ dsn: config.sentry.dsn });
// Sentry.Handlers.requestHandler should be the first middleware
app.use(Sentry.Handlers.requestHandler());
}
};
const appData = {
sentryDsn: process.env.SENTRY_PUBLIC_DSN,
sentryEnv: process.env.SENTRY_ENVIRONMENT,
};
/* configure Sentry */
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.SENTRY_ENVIRONMENT,
});
/* configure the express server */
const server = express();
// the first middleware must be the sentry request handler
server.use(Sentry.Handlers.requestHandler());
// set CORS and JSON middleware
server.use(cors());
server.use(express.json());
// serve public files
const statics = express.static(path.resolve(__dirname, 'public'));
server.use(statics);
// controllers
server.use('/example', exampleController);
// then fallback
server.use(history());
const renderHtml = () => {
async initSentry() {
if ( isDev || !settings.get( 'system.serverAnalytics' ) ) return
logger.info( 'Enabling Sentry error reporting' )
// Set the sentry release
const release = `${SENTRY_PROJECT}@${version}`
Sentry.init( {
dsn: SENTRY_DSN,
release,
} )
}
export default async function initServer() {
// by default `@sentry/node` is configured with defaultIntegrations
// which capture uncaughtExceptions and unhandledRejections
// see here for more https://github.com/getsentry/sentry-javascript/blob/46a02209bafcbc1603c769476ba0a1eaa450759d/packages/node/src/sdk.ts#L22
Sentry.init({
dsn: process.env.SENTRY_DSN,
release: process.env.SENTRY_RELEASE,
})
}
},
initialize: initializationRequired,
integrations: filterDisabledIntegration(options.clientIntegrations)
.reduce((res, key) => {
res[key] = options.clientIntegrations[key]
return res
}, {})
}
})
}
// Register the server plugin
if (!options.disableServerSide) {
// Initialize Sentry
if (initializationRequired) {
Sentry.init({
dsn: options.dsn,
...options.serverConfig,
integrations: filterDisabledIntegration(options.serverIntegrations)
.map(name => new Integrations[name](options.serverIntegrations[name]))
})
}
process.sentry = Sentry
logger.success('Started logging errors to Sentry')
this.addPlugin({
src: path.resolve(__dirname, 'sentry.server.js'),
fileName: 'sentry.server.js',
mode: 'server'
})
this.nuxt.hook('render:setupMiddleware', app => app.use(Sentry.Handlers.requestHandler()))
constructor() {
this.server = express();
// initializing Sentry for bug track managing
Sentry.init(sentryConfig);
// it`s important to execute in order to
// apply the middlewares and routers
this.middlewares();
this.routes();
this.exceptionHandler(); // handling errors for user interface
}