Improve error handling

cshd
Dragory 2020-11-04 23:13:45 +02:00
parent e5172612e9
commit 717072a415
No known key found for this signature in database
GPG Key ID: 5F387BA66DF8AAC1
1 changed files with 31 additions and 14 deletions

View File

@ -17,16 +17,45 @@ try {
} }
// Error handling // Error handling
// Force crash on unhandled rejections and uncaught exceptions.
// Use something like forever/pm2 to restart.
const MAX_STACK_TRACE_LINES = 8;
function errorHandler(err) { function errorHandler(err) {
// Unknown message types (nitro boosting messages at the time) should be safe to ignore // Unknown message types (nitro boosting messages at the time) should be safe to ignore
if (err && err.message && err.message.startsWith("Unhandled MESSAGE_CREATE type")) { if (err && err.message && err.message.startsWith("Unhandled MESSAGE_CREATE type")) {
return; return;
} }
// For everything else, crash with the error if (err) {
console.error(err); if (typeof err === "string") {
console.error(`Error: ${err}`);
} else if (err instanceof utils.BotError) {
// Leave out stack traces for BotErrors (the message has enough info)
console.error(`Error: ${err.message}`);
} else {
// Truncate long stack traces for other errors
const stack = err.stack || "";
let stackLines = stack.split("\n");
if (stackLines.length > (MAX_STACK_TRACE_LINES + 2)) {
stackLines = stackLines.slice(0, MAX_STACK_TRACE_LINES);
stackLines.push(` ...stack trace truncated to ${MAX_STACK_TRACE_LINES} lines`);
}
const finalStack = stackLines.join("\n");
if (err.code) {
console.error(`Error ${err.code}: ${finalStack}`);
} else {
console.error(`Error: ${finalStack}`);
}
}
} else {
console.error("Unknown error occurred");
}
process.exit(1); process.exit(1);
} }
process.on("uncaughtException", errorHandler); process.on("uncaughtException", errorHandler);
process.on("unhandledRejection", errorHandler); process.on("unhandledRejection", errorHandler);
@ -48,18 +77,6 @@ const utils = require("./utils");
const main = require("./main"); const main = require("./main");
const knex = require("./knex"); const knex = require("./knex");
// Force crash on unhandled rejections (use something like forever/pm2 to restart)
process.on("unhandledRejection", err => {
if (err instanceof utils.BotError || (err && err.code)) {
// We ignore stack traces for BotErrors (the message has enough info) and network errors from Eris (their stack traces are unreadably long)
console.error(`Error: ${err.message}`);
} else {
console.error(err);
}
process.exit(1);
});
(async function() { (async function() {
// Make sure the database is up to date // Make sure the database is up to date
const [completed, newMigrations] = await knex.migrate.list(); const [completed, newMigrations] = await knex.migrate.list();