diff --git a/src/invoker.ts b/src/invoker.ts index 044e8ebc..b7ecff28 100644 --- a/src/invoker.ts +++ b/src/invoker.ts @@ -28,7 +28,7 @@ import * as http from 'http'; import * as onFinished from 'on-finished'; import {FUNCTION_STATUS_HEADER_FIELD} from './types'; -import {logAndSendError} from './logger'; +import {sendCrashResponse} from './logger'; import {isBinaryCloudEvent, getBinaryCloudEventContext} from './cloudevents'; import { HttpFunction, @@ -111,7 +111,7 @@ function makeHttpHandler(execute: HttpFunction): express.RequestHandler { console.error(`Exception from a finished function: ${err}`); } else { res.locals.functionExecutionFinished = true; - logAndSendError(err, res); + sendCrashResponse({err, res}); } }); d.run(() => { @@ -305,16 +305,20 @@ export class ErrorHandler { register() { process.on('uncaughtException', err => { console.error('Uncaught exception'); - logAndSendError(err, latestRes, killInstance); + sendCrashResponse({err, res: latestRes, callback: killInstance}); }); process.on('unhandledRejection', err => { console.error('Unhandled rejection'); - logAndSendError(err, latestRes, killInstance); + sendCrashResponse({err, res: latestRes, callback: killInstance}); }); process.on('exit', code => { - logAndSendError(new Error(`Process exited with code ${code}`), latestRes); + sendCrashResponse({ + err: new Error(`Process exited with code ${code}`), + res: latestRes, + silent: code === 0, + }); }); ['SIGINT', 'SIGTERM'].forEach(signal => { diff --git a/src/logger.ts b/src/logger.ts index 6073b8ef..a014ca85 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -22,13 +22,21 @@ import {FUNCTION_STATUS_HEADER_FIELD} from './types'; * @param res Express response object. * @param callback A function to be called synchronously. */ -export function logAndSendError( +export function sendCrashResponse({ + err, + res, + callback, + silent = false, +}: { // eslint-disable-next-line @typescript-eslint/no-explicit-any - err: Error | any, - res: express.Response | null, - callback?: Function -) { - console.error(err.stack || err); + err: Error | any; + res: express.Response | null; + callback?: Function; + silent?: boolean; +}) { + if (!silent) { + console.error(err.stack || err); + } // If user function has already sent response headers, the response with // error message cannot be sent. This check is done inside the callback,