Handle unhandled errors by exiting with non-zero code

This commit is contained in:
Nate 2025-12-23 13:00:23 -05:00
parent 9f5f1fc152
commit d31d6b6fc4
2 changed files with 26 additions and 3 deletions

View file

@ -35,6 +35,9 @@ let lastCtrlCTime: number;
// Agent ID for serve mode - set when serve command is invoked with --id
let agentId: string | undefined;
// Track whether any unhandled errors occurred during execution
let hasUnhandledError = false;
// Initialize state immediately to avoid temporal dead zone issues with exported functions
(function initializeTUIState() {
tuiUnmount = null;
@ -48,6 +51,11 @@ export function setAgentId(id: string | undefined) {
agentId = id;
}
// Check if any unhandled errors occurred during execution
export function hadUnhandledError(): boolean {
return hasUnhandledError;
}
// Register TUI cleanup function for graceful shutdown
export function setTUIUnmount(unmount: () => void) {
tuiUnmount = unmount;
@ -121,6 +129,9 @@ async function reportUnhandledErrorToApi(error: Error): Promise<void> {
// Add global error handlers to prevent uncaught errors from crashing the process
process.on("unhandledRejection", (reason, promise) => {
// Mark that an unhandled error occurred - this will cause non-zero exit
hasUnhandledError = true;
// Extract useful information from the reason
const errorDetails = {
promiseString: String(promise),
@ -149,17 +160,20 @@ process.on("unhandledRejection", (reason, promise) => {
}
// Note: Sentry capture is handled by logger.error() above
// Don't exit the process, just log the error
// Don't exit the process immediately, but hasUnhandledError will cause non-zero exit later
});
process.on("uncaughtException", (error) => {
// Mark that an unhandled error occurred - this will cause non-zero exit
hasUnhandledError = true;
logger.error("Uncaught Exception:", error);
// Report to API if running in serve mode
reportUnhandledErrorToApi(error).catch(() => {
// Silently fail if API reporting errors - already logged in helper
});
// Note: Sentry capture is handled by logger.error() above
// Don't exit the process, just log the error
// Don't exit the process immediately, but hasUnhandledError will cause non-zero exit later
});
// keyboard interruption handler for non-TUI flows

View file

@ -1,5 +1,6 @@
import type { ChatHistoryItem } from "core/index.js";
import { hadUnhandledError } from "../index.js";
import { sentryService } from "../sentry.js";
import { getSessionUsage } from "../session.js";
import { telemetryService } from "../telemetry/telemetryService.js";
@ -140,6 +141,10 @@ function displaySessionUsage(): void {
/**
* Exit the process after flushing telemetry and error reporting.
* Use this instead of process.exit() to avoid losing metrics/logs.
*
* If any unhandled errors occurred during execution and the requested
* exit code is 0 (success), this will exit with code 1 instead to
* signal that the process encountered errors.
*/
export async function gracefulExit(code: number = 0): Promise<void> {
// Display session usage breakdown in verbose mode
@ -159,6 +164,10 @@ export async function gracefulExit(code: number = 0): Promise<void> {
logger.debug("Sentry flush error (ignored)", err as any);
}
// If we're trying to exit with success (0) but had unhandled errors,
// exit with 1 instead to signal failure
const finalCode = code === 0 && hadUnhandledError() ? 1 : code;
// Exit the process
process.exit(code);
process.exit(finalCode);
}