Catch unhandled rejections in background worker

Previously, an unhandled promise rejection in the background worker would crash the process. This way we log it and don't crash.
This commit is contained in:
Kyle Corbitt
2023-08-18 19:03:54 -07:00
parent ef1f9458f4
commit 947eba3216
3 changed files with 55 additions and 0 deletions

View File

@@ -3,6 +3,7 @@
// https://docs.sentry.io/platforms/javascript/guides/nextjs/
import * as Sentry from "@sentry/nextjs";
import { isError } from "lodash-es";
import { env } from "~/env.mjs";
if (env.NEXT_PUBLIC_SENTRY_DSN) {
@@ -15,4 +16,10 @@ if (env.NEXT_PUBLIC_SENTRY_DSN) {
// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,
});
} else {
// Install local debug exception handler for rejected promises
process.on("unhandledRejection", (reason) => {
const reasonDetails = isError(reason) ? reason?.stack : reason;
console.log("Unhandled Rejection at:", reasonDetails);
});
}

View File

@@ -0,0 +1,47 @@
import "dotenv/config";
import defineTask from "./defineTask";
import { type TaskList, run } from "graphile-worker";
import { env } from "~/env.mjs";
import "../../../sentry.server.config";
export type TestTask = { i: number };
// When a new eval is created, we want to run it on all existing outputs, but return the new eval first
export const testTask = defineTask<TestTask>("testTask", (task) => {
console.log("ran task ", task.i);
void new Promise((_resolve, reject) => setTimeout(reject, 500));
return Promise.resolve();
});
const registeredTasks = [testTask];
const taskList = registeredTasks.reduce((acc, task) => {
acc[task.task.identifier] = task.task.handler;
return acc;
}, {} as TaskList);
// process.on("unhandledRejection", (reason, promise) => {
// console.log("Unhandled Rejection at:", reason?.stack || reason);
// });
// Run a worker to execute jobs:
const runner = await run({
connectionString: env.DATABASE_URL,
concurrency: 10,
// Install signal handlers for graceful shutdown on SIGINT, SIGTERM, etc
noHandleSignals: false,
pollInterval: 1000,
taskList,
});
console.log("Worker successfully started");
for (let i = 0; i < 10; i++) {
await testTask.enqueue({ i });
await new Promise((resolve) => setTimeout(resolve, 1000));
}
await runner.promise;

View File

@@ -1,5 +1,6 @@
import { type TaskList, run } from "graphile-worker";
import "dotenv/config";
import "../../../sentry.server.config";
import { env } from "~/env.mjs";
import { queryModel } from "./queryModel.task";