This function I register with atexit to run whenever the script is completing.
        A catch-all for uncaught exceptions, setting status flag file to failed.
345069
def _exit_handler(self):
        

        # TODO: consider handling sys.stderr/sys.stdout exceptions related to
        # TODO (cont.): order of interpreter vs. subprocess shutdown signal receipt.
        # TODO (cont.): see https://bugs.python.org/issue11380


        # Make the cleanup file executable if it exists
        if os.path.isfile(self.cleanup_file):
            # Make the cleanup file self destruct.
            with open(self.cleanup_file, "a") as myfile:
                myfile.write("rm " + self.cleanup_file + "\n")
            os.chmod(self.cleanup_file, 0o755)

        # If the pipeline hasn't completed successfully, or already been marked
        # as failed, then mark it as failed now.

        if not self._has_exit_status:
            print("Pipeline status: {}".format(self.status))
            self.fail_pipeline(Exception("Pipeline failure. See details above."))

        if self.tee:
            self.tee.kill()
100438
def on_complete(env)
      status_code   = env[:status].to_i
      service_error = Github::Error::ServiceError
      error_class = service_error.error_mapping[status_code]
      if !error_class and (400...600) === status_code
        error_class = service_error
      end
      raise error_class.new(env) if error_class
    end
1111854
public static function catchFatalErrors(Application $app, $flush = true)
    {
        if (self::$screen !== null) {
            echo self::$screen;

            return;
        }

        // Get last error, if any
        $error = error_get_last();

        // Let Whoops handle AJAX requested fatal errors
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
            return;
        }

        if (($error['type'] === E_ERROR || $error['type'] === E_PARSE)) {
            $html = self::$html;

            // Flush the early error data buffered output from catchFatalErrorsEarly()
            if ($flush) {
                Response::closeOutputBuffers(0, false);
            }

            // Detect if we're being called from a core, an extension or vendor
            $isBoltCoreError = strpos($error['file'], $app['resources']->getPath('rootpath/src'));
            $isVendorError = strpos($error['file'], $app['resources']->getPath('rootpath/vendor'));
            $isExtensionError = strpos($error['file'], $app['resources']->getPath('extensions'));

            // Assemble error trace
            $errorblock = '<code style="display:block; white-space: pre-wrap;">Error: ' . $error['message'] . '</code><br>';
            $errorblock .= '<code>File:  ' . $error['file'] . '</code><br>';
            $errorblock .= '<code>Line:  ' . $error['line'] . '</code><br><br>';

            if ($isBoltCoreError === 0) {
                $html = str_replace('%error_title%', 'PHP Fatal error: Bolt core', $html);
                $html = str_replace('%info%', '', $html);
                $message = $errorblock;
            } elseif ($isVendorError === 0) {
                $html = str_replace('%error_title%', 'PHP Fatal error: Vendor library', $html);
                $html = str_replace('%info%', '', $html);
                $message = $errorblock;
            } elseif ($isExtensionError === 0) {
                $base = str_replace($app['resources']->getPath('extensions'), '', $error['file']);
                $parts = explode(DIRECTORY_SEPARATOR, ltrim($base, '/'));
                $package = $parts[1] . '/' . $parts[2];

                $html = str_replace('%error_title%', 'PHP Fatal error: Bolt extensions', $html);
                $html = str_replace(
                    '%info%',
                    '<p>You will only be able to continue by disabling the extension by adding the following to app/config/extensions.yml:</p>' .
                    '<p><code style="display:block;">' . $parts[1] . ':<br>' .
                    '&nbsp;&nbsp;&nbsp;&nbsp;' . $parts[2] . ': false</code></p>',
                    $html
                );
                $message = '<h4>There is a fatal error in the \'' . $package . '\' extension ' .
                    'loaded on your Bolt Installation.<h4>';
                $message .= $errorblock;
            } else {
                // Unknown
                $html = str_replace('%error_title%', 'PHP Fatal error: Bolt generic', $html);
                $html = str_replace('%info%', '', $html);
                $message = $errorblock;
            }

            $message = nl2br($message);
            $html = str_replace('%error%', $message, $html);

            // Determine if we're on the command line. If so, don't output HTML.
            if (PHP_SAPI == 'cli') {
                $html = self::cleanHTML($html);
            }

            echo str_replace($app['resources']->getPath('rootpath'), '', $html);
        }

        echo self::$screen;
    }
1319998
function (src, success, error) {
		var s = document.createElement('script');
		s.src = src;
		s.async = true;
		s.onload = function() {
			document.body.removeChild(s);
			success && success();
		};
		s.onerror = function() {
			document.body.removeChild(s);
			error && error();
		};
		document.body.appendChild(s);
	}
463288
def on_terminate(func):
    """"""
    def exit_function(*args):
        func()
        exit(0)
    signal.signal(signal.SIGTERM, exit_function)
304741
final public static function shutdownFunctionHandler()
    {
        $lasterror = error_get_last();
        if (!FEnv::isset("framework.env")) {
            die($lasterror['message']);
        }

        if (isset($lasterror['type']) == true) {
            if ($lasterror['type'] === E_ERROR) {
                $mess = explode("Stack trace", $lasterror['message']);
                throw new Server500(new \ArrayObject(array("explain" => $mess[0],
                    "type_error" => self::errorMap($lasterror['type']),
                    "file_error" => $lasterror["file"], "line_error" => $lasterror["line"])));
            } elseif ($lasterror['type'] === E_PARSE) {
                $mess = explode("Stack trace", $lasterror['message']);
                throw new Server500(new \ArrayObject(array("explain" => $mess[0],
                    "type_error" => self::errorMap($lasterror['type']),
                    "file_error" => $lasterror["file"], "line_error" => $lasterror["line"])));
            } elseif ($lasterror['type'] === E_WARNING) {
                $mess = explode("Stack trace", $lasterror['message']);
                throw new Server500(new \ArrayObject(array("explain" => $mess[0],
                    "type_error" => self::errorMap($lasterror['type']),
                    "file_error" => $lasterror["file"], "line_error" => $lasterror["line"])));
            } else {
                trigger_error($lasterror['message']);
            }
        }

        exit(1);
    }
696038
protected function registerErrorHandle(): void
    {
        \set_error_handler([$this, 'handleError']);
        \set_exception_handler([$this, 'handleException']);
        \register_shutdown_function(function () {
            if ($e = \error_get_last()) {
                $this->handleError($e['type'], $e['message'], $e['file'], $e['line']);
            }
        });
    }
1135505
function onInterrupted() {
  try {
    if (fs.existsSync(tmpZipFilePath)) {
      fs.unlinkSync(tmpZipFilePath)
    }
    if (fs.existsSync(binPath)) {
      fs.unlinkSync(binPath)
    }
  } catch (e) {
    console.warn(e)
  }
  console.log('install is aborted')
  process.exit(1)
}
136068
static public function catchFatal()
    {
        $error = error_get_last();
        if ($error["type"] == E_ERROR 
            || $error['type'] == E_PARSE 
            || $error['type'] == E_CORE_ERROR
            || $error['type'] == E_COMPILE_ERROR) {
            self::errorHandler($error["type"], $error["message"], $error["file"], $error["line"]);
            /**
              Put fatals in the error log as well as the debug log
              For good measure, put them in STDERR too. Try to
              ensure somebody notices.
            */
            $msg = $error['message']
                . ' Line ' . $error['line']
                . ', File ' . $error['file'];
            self::$logger->error($msg);
            file_put_contents('php://stderr', $msg, FILE_APPEND);
        }
    }
209067
function onwritten(err) {
  if (err) return console.error(err)

  collector.cleanAllResources().disable()

  // allow `close` 'after' and `destroy` to fire
  tick(2, () => {
    collector
      .processStacks()
      .stringifyBuffers()

    // save('write-fs-only', Array.from(collector.fileSystemActivities))
    // save('write-fs-all', Array.from(collector.activities))
  })
}
701354
function handleUncaught (server, enabled) {
  if (!enabled) {
    return
  }

  process.once('uncaughtException', (err) => {
    err = Object.assign({ source: getErrorSource(err) }, objectify(err))
    server.log(['uncaught', 'error'], { err })
    process.exit(1)
  })
}
959141
function runAfterSuccessScripts() {
  const autorelease =
    pkg.version === '0.0.0-semantically-released' &&
    parseEnv('TRAVIS', false) &&
    process.env.TRAVIS_BRANCH === 'master' &&
    !parseEnv('TRAVIS_PULL_REQUEST', false)

  const reportCoverage = hasFile('coverage') && !parseEnv('SKIP_CODECOV', false)

  if (!autorelease && !reportCoverage) {
    console.log(
      'No need to autorelease or report coverage. Skipping travis-after-success script...',
    )
  } else {
    const result = spawn.sync(
      resolveBin('concurrently'),
      getConcurrentlyArgs(
        {
          codecov: reportCoverage
            ? `echo installing codecov && npx -p codecov@3 -c 'echo running codecov && codecov'`
            : null,
          release: autorelease
            ? `echo installing semantic-release && npx -p semantic-release@15 -c 'echo running semantic-release && semantic-release'`
            : null,
        },
        {killOthers: false},
      ),
      {stdio: 'inherit'},
    )

    process.exit(result.status)
  }
}
1218224
function (clt_name, op, err, onFail, is_exception) {

	var msg = 'DB ' + op + ' error for [' + clt_name + ']';
	LOG.error(msg, 'SR.DB');
	LOG.error(err, 'SR.DB');
	if (typeof err.stack !== 'undefined') {
		LOG.error(err.stack, 'SR.DB');
		msg += ('\n\n' + err.stack);
	}
	UTIL.safeCall(onFail, err);

	if (is_exception) {
		return;
	}

	// notify project admin if it's not code exception
	// NOTE: only project admins are notified
	UTIL.notifyAdmin(
		'[SR DB error: ' + clt_name + ']',
		msg
	);
}
1176015
function finish(err) {
      // Run callbacks when we have an error,
      // or when import parsing is complete.
      if (err || self.isParsed()) {
        // Cache the file after parsing:
        _.cacheFile(self);

        // Run all callbacks:
        for (var i=0; i < self._cb.length; i++) self._cb[i](err, self);
        self._cb = [];
      }
    }
228095
public function handleFatalError()
    {
        // When running under codeception, a Yii application won't actually exist, so we just have to eat it here...
        if (is_object(Yii::$app))
        {
            // Call into Bugsnag client's errorhandler since this will potentially kill the script below 
            Yii::$app->bugsnag->runShutdownHandler();
        }

        parent::handleFatalError();
    }
677733
function complete ( err, msg ){
      b9.off('hello', success ); // cleanup
      // optional callback, error-first...
      if ( typeof callback == 'function' ){
        callback( err, msg );
      }
    }
21158
function onFileReady(err, data) {
    if (err) {
      if (onDone) onDone(err);
      else console.error('>>>' + err);
      return;
    }

    var fileContent = data.toString();

    var options = {
      gfm: (flavour === 'gfm') ? true : false,
      breaks: true,
      tables: true,
      sanitize: true
    };

    if (highlight) {
      options['highlight'] = function(code, lang, callback) {
        pygmentize({lang: lang, format: 'html'}, code, function(err, result) {
          if (err) {
            callback(err);
          }
          callback(err, result.toString());
        });
      }
    }

    //======================================================
    // Call marked to parse the file content
    //======================================================
    if (this.debug) console.error('>>>starting to get code');
    try {
      marked.setOptions(options);
      marked(fileContent, getCode.bind(this));
    } catch(err) {
      if (onDone) onDone(err)
      else console.error('>>>' + err);
    }

    //======================================================
    // Enhance the output of marked with optional header
    // or trailer. Linkify if context specified.
    //======================================================
    function getCode(err, code) {
      if (err) {
        if (onDone) onDone(err)
        else console.error('>>>' + err);
        return;
      }

      if (htmlTemplate) {
        this.cat(fs.readFileSync(htmlTemplate));

        let mdCode = ''
        if (context) {
          mdCode = linkify(code, context);
        } else {
          mdCode = code;
        }
        this.replace(mdCode);
      } else {
        if (stylesheet || title) {
          if (titleText == null) titleText = fileName;
          this.cat('<!DOCTYPE html>\n' +
                   '<html>\n' +
                   '<head>\n' +
                   '  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>' + 
                   '  <title>' + titleText + '</title>\n');
          if (stylesheet) {
            this.cat('  <link rel="stylesheet" href="' + stylesheet + '">\n');
          }
          this.cat('</head>\n<body>\n' );
        }

        if (context) {
          this.cat( linkify(code, context) );
        } else {
          this.cat( code );
        }

        if (stylesheet || title) {
          this.cat( '</body>\n</html>\n' );
        }  
      }
      
      if (this.debug) console.error('>>>finished getting code');
      this.done = true;
      if (onDone) onDone();
    } // end getCode
  }