Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions.
179070
def _install_exception_handler(self):
        
        def handler(t, value, traceback):
            if self.args.verbose:
                sys.__excepthook__(t, value, traceback)
            else:
                sys.stderr.write('%s\n' % unicode(value).encode('utf-8'))

        sys.excepthook = handler
464916
def install_hook(dialog=SimpleExceptionDialog, invoke_old_hook=False, **extra):
    
    global _old_hook
    assert _old_hook is None

    def new_hook(etype, eval, trace):
        gobject.idle_add(dialog_handler, dialog, etype, eval, trace, extra)
        if invoke_old_hook:
            _old_hook(etype, eval, trace)

    _old_hook = sys.excepthook
    sys.excepthook = new_hook
73711
def install_pdb_handler():
  """"""

  import signal
  import pdb

  def handler(_signum, _frame):
    pdb.set_trace()

  signal.signal(signal.SIGQUIT, handler)
532589
function setupHandlers() {

    function terminate(err) {
        util.log('Uncaught Error: ' + err.message);
        console.log(err.stack);
        if (proc.shutdownHook) {
            proc.shutdownHook(err, gracefulShutdown);
        }
    }

    process.on('uncaughtException', terminate);

    process.addListener('SIGINT', gracefulShutdown);

    process.addListener('SIGHUP', function () {
        util.log('RECIEVED SIGHUP signal, reloading log files...');
        reload(argv);
    });

}
545291
def replace_exceptions(
    old_to_new_exceptions: Dict[Type[BaseException], Type[BaseException]]
) -> Callable[..., Any]:
    
    old_exceptions = tuple(old_to_new_exceptions.keys())

    def decorator(to_wrap: Callable[..., Any]) -> Callable[..., Any]:
        @functools.wraps(to_wrap)
        # String type b/c pypy3 throws SegmentationFault with Iterable as arg on nested fn
        # Ignore so we don't have to import `Iterable`
        def wrapper(
            *args: Iterable[Any], **kwargs: Dict[str, Any]
        ) -> Callable[..., Any]:
            try:
                return to_wrap(*args, **kwargs)
            except old_exceptions as err:
                try:
                    raise old_to_new_exceptions[type(err)] from err
                except KeyError:
                    raise TypeError(
                        "could not look up new exception to use for %r" % err
                    ) from err

        return wrapper

    return decorator
395108
def excepthook(exc_type, exc_value, tracebackobj):
    
    separator = "-" * 80
    notice = "The following error was triggered:"

    now = datetime.now().strftime("%Y-%m-%d, %H:%M:%S")

    info = StringIO()
    traceback.print_tb(tracebackobj, None, info)
    info.seek(0)
    info = info.read()

    errmsg = f"{exc_type}\t \n{exc_value}"
    sections = [now, separator, errmsg, separator, info]
    msg = "\n".join(sections)

    print(''.join(traceback.format_tb(tracebackobj)))
    print('{0}: {1}'.format(exc_type, exc_value))

    QtWidgets.QMessageBox.warning(None, notice, traceback.format_exc())
1032718
synchronized void insert_except(DevFailed res, TimeVal when, TimeVal needed)
	{
		ring.insert_except(res,when);
		needed_time = needed;
	}
726939
static function errorChoosenAction( $errorCode, &$installParameters, $description, $handlerType, $resetError = true )
    {
        if ( isset( $installParameters['non-interactive'] ) && $installParameters['non-interactive'] )
        {
            if ( $description )
            {
                eZDebug::writeNotice( $description, 'Package installation conflict' );
            }
            return eZPackage::NON_INTERACTIVE;
        }

        if ( isset( $installParameters['error_default_actions'][$handlerType][$errorCode] ) )
        {
            if ( $resetError && count( $installParameters['error'] ) )
                $installParameters['error'] = array();
            return $installParameters['error_default_actions'][$handlerType][$errorCode];
        }

        if ( isset( $installParameters['error']['error_code'] ) &&
             $installParameters['error']['error_code'] == $errorCode )
        {
            if ( isset( $installParameters['error']['choosen_action'] ) )
            {
                $choosenAction = $installParameters['error']['choosen_action'];
                if ( $resetError )
                    $installParameters['error'] = array();
                return $choosenAction;
            }
        }
        return false;
    }
419830
def catch_exceptions(orig_func):
    """"""

    @functools.wraps(orig_func)
    def catch_exceptions_wrapper(self, *args, **kwargs):
        try:
            return orig_func(self, *args, **kwargs)
        except arvados.errors.ApiError as e:
            logging.exception("Failure")
            return {"msg": e._get_reason(), "status_code": e.resp.status}, int(e.resp.status)
        except subprocess.CalledProcessError as e:
            return {"msg": str(e), "status_code": 500}, 500
        except MissingAuthorization:
            return {"msg": "'Authorization' header is missing or empty, expecting Arvados API token", "status_code": 401}, 401
        except ValueError as e:
            return {"msg": str(e), "status_code": 400}, 400
        except Exception as e:
            return {"msg": str(e), "status_code": 500}, 500

    return catch_exceptions_wrapper
316178
def _sysv_enable(name):
    '''
    
    '''
    if not _service_is_chkconfig(name) and not _chkconfig_add(name):
        return False
    cmd = '/sbin/chkconfig {0} on'.format(name)
    return not __salt__['cmd.retcode'](cmd, python_shell=False)
723353
def install(
        config_file, store,
        overwrite=False, hooks=False, hook_type='pre-commit',
        skip_on_missing_conf=False,
):
    """"""
    if cmd_output('git', 'config', 'core.hooksPath', retcode=None)[1].strip():
        logger.error(
            'Cowardly refusing to install hooks with `core.hooksPath` set.\n'
            'hint: `git config --unset-all core.hooksPath`',
        )
        return 1

    hook_path, legacy_path = _hook_paths(hook_type)

    mkdirp(os.path.dirname(hook_path))

    # If we have an existing hook, move it to pre-commit.legacy
    if os.path.lexists(hook_path) and not is_our_script(hook_path):
        shutil.move(hook_path, legacy_path)

    # If we specify overwrite, we simply delete the legacy file
    if overwrite and os.path.exists(legacy_path):
        os.remove(legacy_path)
    elif os.path.exists(legacy_path):
        output.write_line(
            'Running in migration mode with existing hooks at {}\n'
            'Use -f to use only pre-commit.'.format(legacy_path),
        )

    params = {
        'CONFIG': config_file,
        'HOOK_TYPE': hook_type,
        'INSTALL_PYTHON': sys.executable,
        'SKIP_ON_MISSING_CONFIG': skip_on_missing_conf,
    }

    with io.open(hook_path, 'w') as hook_file:
        contents = resource_text('hook-tmpl')
        before, rest = contents.split(TEMPLATE_START)
        to_template, after = rest.split(TEMPLATE_END)

        before = before.replace('#!/usr/bin/env python3', shebang())

        hook_file.write(before + TEMPLATE_START)
        for line in to_template.splitlines():
            var = line.split()[0]
            hook_file.write('{} = {!r}\n'.format(var, params[var]))
        hook_file.write(TEMPLATE_END + after)
    make_executable(hook_path)

    output.write_line('pre-commit installed at {}'.format(hook_path))

    # If they requested we install all of the hooks, do so.
    if hooks:
        install_hooks(config_file, store)

    return 0
987220
function exceptionWithHostPort(err, syscall, address, port, additional) {
  // TODO(joyeecheung): We have to use the type-checked
  // getSystemErrorName(err) to guard against invalid arguments from users.
  // This can be replaced with [ code ] = errmap.get(err) when this method
  // is no longer exposed to user land.
  if (util === undefined) util = require('util');
  const code = util.getSystemErrorName(err);
  let details = '';
  if (port && port > 0) {
    details = ` ${address}:${port}`;
  } else if (address) {
    details = ` ${address}`;
  }
  if (additional) {
    details += ` - Local (${additional})`;
  }

  // eslint-disable-next-line no-restricted-syntax
  const ex = new Error(`${syscall} ${code}${details}`);
  // TODO(joyeecheung): errno is supposed to err, like in uvException
  ex.code = ex.errno = code;
  ex.syscall = syscall;
  ex.address = address;
  if (port) {
    ex.port = port;
  }

  Error.captureStackTrace(ex, exceptionWithHostPort);
  return ex;
}
950034
def system_exit(object):
    

    @functools.wraps(object)
    def system_exit_wrapper(*args, **kwargs):
        """
        Handles proper system exit in case of critical exception.

        :param \*args: Arguments.
        :type \*args: \*
        :param \*\*kwargs: Keywords arguments.
        :type \*\*kwargs: \*\*
        """

        try:
            if object(*args, **kwargs):
                foundations.core.exit(0)
        except Exception as error:
            sys.stderr.write("\n".join(foundations.exceptions.format_exception(*sys.exc_info())))
            foundations.core.exit(1)

    return system_exit_wrapper
260245
def handle(): # pragma: no cover
    

    try:
        cli = ZappaCLI()
        sys.exit(cli.handle())
    except SystemExit as e: # pragma: no cover
        cli.on_exit()
        sys.exit(e.code)

    except KeyboardInterrupt: # pragma: no cover
        cli.on_exit()
        sys.exit(130)
    except Exception as e:
        cli.on_exit()

        click.echo("Oh no! An " + click.style("error occurred", fg='red', bold=True) + "! :(")
        click.echo("\n==============\n")
        import traceback
        traceback.print_exc()
        click.echo("\n==============\n")
        shamelessly_promote()

        sys.exit(-1)
588576
def forward_exception(self, etype, evalue, tb):
        
        self._excepthook(etype, evalue, tb)
443804
def _CleanupInstall(self):
    """"""
    if os.path.exists(self.install_path):
      shutil.rmtree(self.install_path)
      if os.path.exists(self.install_path):
        raise RuntimeError("Install path still exists: %s" % self.install_path)

    # Deliberately don't check return code, since service may not be installed.
    subprocess.call(["sc", "stop", self.service_name])
749120
def handling_exceptions(self):
        """"""
        try:
            if self.using_jobs:
                with handling_broken_process_pool():
                    yield
            else:
                yield
        except SystemExit as err:
            self.register_error(err.code)
        except BaseException as err:
            if isinstance(err, CoconutException):
                logger.display_exc()
            elif not isinstance(err, KeyboardInterrupt):
                traceback.print_exc()
                printerr(report_this_text)
            self.register_error(errmsg=err.__class__.__name__)