pokemon-showdown/lib/crashlogger.ts
Guangcong Luo 3d68248efa Update to latest eslint
We're skipping two major typescript-eslint versions, so there are a
bunch of changes here, including:

- it's catching a lot of things it didn't catch in the past, for
  reasons unclear to me

- no-unused-vars has to be explicitly disabled in global-types now

- a lot of `ts-ignore`s were never necessary and have been fixed

- Crashlogger can now handle being thrown things that aren't errors.
  This has never been a problem in the past, but to satisfy TypeScript
	we might as well not die in a fire on the off chance someone tries to
	`throw null` or something.
2020-09-29 15:28:08 -07:00

91 lines
2.3 KiB
TypeScript

/**
* Crash logger
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Logs crashes, sends an e-mail notification if you've set up
* config.js to do that.
*
* @license MIT
*/
import * as fs from 'fs';
import * as path from 'path';
const CRASH_EMAIL_THROTTLE = 5 * 60 * 1000; // 5 minutes
const LOCKDOWN_PERIOD = 30 * 60 * 1000; // 30 minutes
const logPath = path.resolve(__dirname, '../logs/errors.txt');
let lastCrashLog = 0;
let transport: any;
/**
* Logs when a crash happens to console, then e-mails those who are configured
* to receive them.
*/
export function crashlogger(
error: Error | string, description: string, data: AnyObject | null = null
): string | null {
const datenow = Date.now();
let stack = (typeof error === 'string' ? error : error?.stack) || '';
if (data) {
stack += `\n\nAdditional information:\n`;
for (const k in data) {
stack += ` ${k} = ${data[k]}\n`;
}
}
console.error(`\nCRASH: ${stack}\n`);
const out = fs.createWriteStream(logPath, {flags: 'a'});
out.on('open', () => {
out.write(`\n${stack}\n`);
out.end();
}).on('error', (err: Error) => {
console.error(`\nSUBCRASH: ${err.stack}\n`);
});
if (Config.crashguardemail && ((datenow - lastCrashLog) > CRASH_EMAIL_THROTTLE)) {
lastCrashLog = datenow;
if (!transport) {
try {
require.resolve('nodemailer');
} catch (e) {
throw new Error(
'nodemailer is not installed, but it is required if Config.crashguardemail is configured! ' +
'Run npm install --no-save nodemailer and restart the server.'
);
}
}
let text = `${description} crashed `;
if (transport) {
text += `again with this stack trace:\n${stack}`;
} else {
try {
transport = require('nodemailer').createTransport(Config.crashguardemail.options);
} catch (e) {
throw new Error("Failed to start nodemailer; are you sure you've configured Config.crashguardemail correctly?");
}
text += `with this stack trace:\n${stack}`;
}
transport.sendMail({
from: Config.crashguardemail.from,
to: Config.crashguardemail.to,
subject: Config.crashguardemail.subject,
text,
}, (err: Error | null) => {
if (err) console.error(`Error sending email: ${err}`);
});
}
if (process.uptime() * 1000 < LOCKDOWN_PERIOD) {
// lock down the server
return 'lockdown';
}
return null;
}