refactor: centralize unhandled rejection setup

This commit is contained in:
Peter Steinberger
2026-01-07 20:59:49 +00:00
parent fd3babc626
commit 9bd439892f
7 changed files with 43 additions and 45 deletions

14
src/infra/bonjour-ciao.ts Normal file
View File

@@ -0,0 +1,14 @@
import { logDebug } from "../logger.js";
import { formatBonjourError } from "./bonjour-errors.js";
export function ignoreCiaoCancellationRejection(reason: unknown): boolean {
const message = formatBonjourError(reason).toUpperCase();
if (!message.includes("CIAO ANNOUNCEMENT CANCELLED")) {
return false;
}
logDebug(
`bonjour: ignoring unhandled ciao rejection: ${formatBonjourError(reason)}`,
);
return true;
}

View File

@@ -0,0 +1,7 @@
export function formatBonjourError(err: unknown): string {
if (err instanceof Error) {
const msg = err.message || String(err);
return err.name && err.name !== "Error" ? `${err.name}: ${msg}` : msg;
}
return String(err);
}

View File

@@ -2,6 +2,8 @@ import os from "node:os";
import { logDebug, logWarn } from "../logger.js";
import { getLogger } from "../logging.js";
import { ignoreCiaoCancellationRejection } from "./bonjour-ciao.js";
import { formatBonjourError } from "./bonjour-errors.js";
import { registerUnhandledRejectionHandler } from "./unhandled-rejections.js";
export type GatewayBonjourAdvertiser = {
@@ -45,14 +47,6 @@ type BonjourService = {
serviceState: string;
};
function formatBonjourError(err: unknown): string {
if (err instanceof Error) {
const msg = err.message || String(err);
return err.name && err.name !== "Error" ? `${err.name}: ${msg}` : msg;
}
return String(err);
}
function serviceSummary(label: string, svc: BonjourService): string {
let fqdn = "unknown";
let hostname = "unknown";
@@ -147,16 +141,7 @@ export async function startGatewayBonjourAdvertiser(
let ciaoCancellationRejectionHandler: (() => void) | undefined;
if (services.length > 0) {
ciaoCancellationRejectionHandler = registerUnhandledRejectionHandler(
(reason) => {
const message = formatBonjourError(reason).toUpperCase();
if (!message.includes("CIAO ANNOUNCEMENT CANCELLED")) {
return false;
}
logDebug(
`bonjour: ignoring unhandled ciao rejection: ${formatBonjourError(reason)}`,
);
return true;
},
ignoreCiaoCancellationRejection,
);
}

View File

@@ -1,3 +1,5 @@
import process from "node:process";
type UnhandledRejectionHandler = (reason: unknown) => boolean;
const handlers = new Set<UnhandledRejectionHandler>();
@@ -24,3 +26,14 @@ export function isUnhandledRejectionHandled(reason: unknown): boolean {
}
return false;
}
export function installUnhandledRejectionHandler(): void {
process.on("unhandledRejection", (reason, _promise) => {
if (isUnhandledRejectionHandled(reason)) return;
console.error(
"[clawdbot] Unhandled promise rejection:",
reason instanceof Error ? (reason.stack ?? reason.message) : reason,
);
process.exit(1);
});
}