Skip to content

Commit

Permalink
Handle errors on stdout/stderr
Browse files Browse the repository at this point in the history
  • Loading branch information
benjie committed Apr 26, 2024
1 parent 2bafad3 commit d4f07c0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
20 changes: 19 additions & 1 deletion src/main.ts
Expand Up @@ -126,8 +126,22 @@ function _reallyRegisterSignalHandlers(logger: Logger) {
}
};

const stdioErrorIgnorer = () => {
// DO NOTHING. Not even write to `@logger` since that might be using stdio
// under the hood, and cause recursive errors.
};
const stdioErrorHandler = () => {
process.stdout.on("error", stdioErrorIgnorer);
process.stdout.off("error", stdioErrorHandler);
process.stderr.on("error", stdioErrorIgnorer);
process.stderr.off("error", stdioErrorHandler);

// Trigger graceful handler
gracefulHandler("SIGPIPE");
};

const gracefulHandler = function (signal: Signal) {
if (_shuttingDownGracefully) {
if (_shuttingDownGracefully || _shuttingDownForcefully) {
logger.error(
`Ignoring '${signal}' (graceful shutdown already in progress)`,
);
Expand Down Expand Up @@ -196,6 +210,8 @@ function _reallyRegisterSignalHandlers(logger: Logger) {
for (const signal of SIGNALS) {
process.on(signal, gracefulHandler);
}
process.stdout.on("error", stdioErrorHandler);
process.stderr.on("error", stdioErrorHandler);
_releaseSignalHandlers = () => {
if (_shuttingDownGracefully || _shuttingDownForcefully) {
logger.warn(`Not unregistering signal handlers as we're shutting down`);
Expand All @@ -206,6 +222,8 @@ function _reallyRegisterSignalHandlers(logger: Logger) {
for (const signal of SIGNALS) {
process.off(signal, gracefulHandler);
}
process.stdout.off("error", stdioErrorHandler);
process.stderr.off("error", stdioErrorHandler);
_registeredSignalHandlers = false;
};
}
Expand Down
2 changes: 1 addition & 1 deletion src/signals.ts
Expand Up @@ -2,7 +2,7 @@ export type Signal =
| "SIGUSR2"
| "SIGINT"
| "SIGTERM"
// | "SIGPIPE"
| "SIGPIPE"
| "SIGHUP"
| "SIGABRT";

Expand Down

0 comments on commit d4f07c0

Please sign in to comment.