A decorator to cleanly exit on a failed call to AWS.
    catch a `botocore.exceptions.ClientError` raised from an action.
    This sort of error is raised if you are targeting a region that
    isn't set up (see, `credstash setup`.
337674
def clean_fail(func):
    '''
    
    '''
    def func_wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except botocore.exceptions.ClientError as e:
            print(str(e), file=sys.stderr)
            sys.exit(1)
    return func_wrapper
347769
def _handle_api_error(self, error):
        
        status_code = error.response.status_code
        message = error.message

        if 403 == status_code:
            raise NewRelicInvalidApiKeyException(message)
        elif 404 == status_code:
            raise NewRelicUnknownApplicationException(message)
        elif 422 == status_code:
            raise NewRelicInvalidParameterException(message)
        else:
            raise NewRelicApiException(message)
749867
def throws_errors(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        response = func(*args, **kwargs)

        # if no status code is provided, assume 400
        if isinstance(response, BugZooException):
            err_jsn = flask.jsonify(response.to_dict())
            return err_jsn, 400

        if isinstance(response, tuple) \
           and isinstance(response[0], BugZooException):
            err = response[0] # type: BugZooException
            err_jsn = flask.jsonify(err.to_dict())
            return (err_jsn, *response[1:])

        return response

    return wrapper
858664
function (err) {
      log.error("Redis client closed " + (err ? err.message : ''));
      this.connected = false;
      this.emit('close', err);
      this.backoff.reset();
      this.backoff.backoff();
    }
1203417
def exit_with_error(message):
    
    click.secho(message, err=True, bg='red', fg='white')
    sys.exit(0)
807764
function onError(err) {
    const ctx = err.client.$ctx;
    npm.events.error(ctx.options, err, {
        cn: npm.utils.getSafeConnection(ctx.cn),
        dc: ctx.dc
    });
}
87528
def threw(cls, spy, error_type=None):
        
        cls.__is_spy(spy)
        if not (spy.threw(error_type)):
            raise cls.failException(cls.message)
1272630
def catch_boto_400(self, message, heading=None, document=None, **info):
        """"""
        try:
            yield
        except ClientError as error:
            if str(error.response["ResponseMetadata"]["HTTPStatusCode"]).startswith("4"):
                if heading or document:
                    print("=" * 80)
                    if heading:
                        print(heading)
                    print(document)
                    print("=" * 80)
                error_message = error.response["Error"]["Message"]
                raise BadAmazon(message, error_message=error_message, error_code=error.response["ResponseMetadata"]["HTTPStatusCode"], **info)
            else:
                raise
475327
def handle_connection_exec(client):
    
    class ExitExecLoop(Exception):
        pass

    def exit():
        raise ExitExecLoop()

    client.settimeout(None)
    fh = os.fdopen(client.detach() if hasattr(client, 'detach') else client.fileno())

    with closing(client):
        with closing(fh):
            try:
                payload = fh.readline()
                while payload:
                    _LOG("Running: %r." % payload)
                    eval(compile(payload, '<manhole>', 'exec'), {'exit': exit}, _MANHOLE.locals)
                    payload = fh.readline()
            except ExitExecLoop:
                _LOG("Exiting exec loop.")
493530
def catch_websocket_connection_errors():
  """"""
  try:
    yield
  except websocket.WebSocketConnectionClosedException:
    raise ConnectionError("Connection already closed. SC2 probably crashed. "
                          "Check the error log.")
  except websocket.WebSocketTimeoutException:
    raise ConnectionError("Websocket timed out.")
  except socket.error as e:
    raise ConnectionError("Socket error: %s" % e)
568294
def handle_error(self, exc=None):
    """"""
    if exc:
      NailgunProtocol.send_stderr(self.request, traceback.format_exc())
    failure_code = 1
    NailgunProtocol.send_exit_with_code(self.request, failure_code)
40256
def _excepthook(self, etype, evalue, trace):
        
        if etype == ArgumentParserError:
            self.exit(code=CRITICAL,
                      message='error: {0}'.format(evalue),
                      extdata=self.parser.format_usage())
        else:
            self.exit(code=UNKNOWN,
                      message='Uncaught exception: {0} - {1}'
                              .format(etype.__name__, evalue),
                      extdata=''.join(traceback.format_tb(trace)))
1103202
function catchClientError(req, res, next) {
  const { end } = res;

  res.end = function() {
    // console.log(`Catch client response : ${req.url} ${res.statusCode}`);
    const errorRoute = Route
      .routes('err')
      .filter((obj) => {
        return obj.extra.status === res.statusCode && obj.route !== req.url;
      });

    if(errorRoute.length > 0 && !isRedirect) {
      return redirect(errorRoute[0], req, res, next);
    }

    isRedirect = false;
    end.apply(res, arguments);
  };

  next();
}
441377
def handle_api_exceptions(
    ctx, opts, context_msg=None, nl=False, exit_on_error=True, reraise_on_error=False
):
    """"""
    # flake8: ignore=C901
    # Use stderr for messages if the output is something else (e.g.  # JSON)
    use_stderr = opts.output != "pretty"

    try:
        yield
    except ApiException as exc:
        if nl:
            click.echo(err=use_stderr)
            click.secho("ERROR: ", fg="red", nl=False, err=use_stderr)
        else:
            click.secho("ERROR", fg="red", err=use_stderr)

        context_msg = context_msg or "Failed to perform operation!"
        click.secho(
            "%(context)s (status: %(code)s - %(code_text)s)"
            % {
                "context": context_msg,
                "code": exc.status,
                "code_text": exc.status_description,
            },
            fg="red",
            err=use_stderr,
        )

        detail, fields = get_details(exc)
        if detail or fields:
            click.echo(err=use_stderr)

            if detail:
                click.secho(
                    "Detail: %(detail)s"
                    % {"detail": click.style(detail, fg="red", bold=False)},
                    bold=True,
                    err=use_stderr,
                )

            if fields:
                for k, v in six.iteritems(fields):
                    field = "%s Field" % k.capitalize()
                    click.secho(
                        "%(field)s: %(message)s"
                        % {
                            "field": click.style(field, bold=True),
                            "message": click.style(v, fg="red"),
                        },
                        err=use_stderr,
                    )

        hint = get_error_hint(ctx, opts, exc)
        if hint:
            click.echo(
                "Hint: %(hint)s" % {"hint": click.style(hint, fg="yellow")},
                err=use_stderr,
            )

        if opts.verbose and not opts.debug:
            if exc.headers:
                click.echo(err=use_stderr)
                click.echo("Headers in Reply:", err=use_stderr)
                for k, v in six.iteritems(exc.headers):
                    click.echo(
                        "%(key)s = %(value)s" % {"key": k, "value": v}, err=use_stderr
                    )

        if reraise_on_error:
            six.reraise(*sys.exc_info())

        if exit_on_error:
            ctx.exit(exc.status or 1)
857872
def catch_exception(exception, message=None):
    
    def decorator(f):
        @click.pass_context
        def new_func(ctx, *args, **kwargs):
            try:
                return ctx.invoke(f, *args, **kwargs)
            except exception as e:
                message1 = message if message is not None else '{}'.format(e)
                click.echo(message1)
                ctx.exit(code=exit_codes.OTHER_FAILURE)
        return update_wrapper(new_func, f)
    return decorator
856977
function handleError(reject) {
  return (e) => {
    // prevent global error throw https://bugzilla.mozilla.org/show_bug.cgi?id=872873
    if (typeof e.preventDefault === 'function') e.preventDefault()
    reject(e.target.error)
  }
}
427300
def exception_handler(exctype, value, traceback):
    
    if exctype == KeyboardInterrupt:
        pypro.console.out('')  # Adds a new line after Ctrl+C character
        pypro.console.err('Canceled')
    elif exctype == PyproException:
        pypro.console.err('[Error] ', value.message)
        exit()
    else:
        sys.__excepthook__(exctype, value, traceback)