Attach payload error handler
967154
protected function attachPayloadErrorHandler() {
        $this->getPayloadInstance();
        if (method_exists($this->instance, 'errorHandler')) {
            $this->di->get(ErrorHandler::class)->addHandler([$this->instance, 'errorHandler']);
        }
    }
161273
async function handleCallError (result) {
  const error = Buffer.from(result.returnValue).toString()
  if (isBase64(error.slice(3))) {
    const decodedError = Buffer.from(error.slice(3), 'base64').toString()
    throw Object.assign(Error(`Invocation failed: ${error}. Decoded: ${decodedError}`), R.merge(result, { error, decodedError }))
  }

  const decodedError = await this.contractDecodeData('string', error)
  throw Object.assign(Error(`Invocation failed: ${error}. Decoded: ${decodedError}`), R.merge(result, { error, decodedError }))
}
914468
def handle_errors(callback, parsed=None, out=sys.stderr):

    """"""

    try:
        if parsed:
            return callback(parsed)
        else:
            return callback()
    except DeploymentError as e:
        traceback.print_exc(file=out)
        print(e, file=out)
        if hasattr(e, 'value') and hasattr(e.value, 'args') and len(e.value.args) > 0 and \
                'open_sftp_client' in e.value.args[0]:
            print('Timeout', file=out)
            return TIMEOUT
        return DEPLOYMENT_ERROR
    except MalformedResponseError as e:
        traceback.print_exc(file=out)
        print(e, file=out)
        if 'Service Unavailable' in e.body:
            return SERVICE_UNAVAILABLE
        return MALFORMED_RESPONSE
    except SystemExit:
        pass
    except:
        traceback.print_exc(file=out)
        return EXCEPTION
1109611
def handle_incoming_response(self, call_id, payload):
        """"""
        self.log.debug('handle_incoming_response: in [typehint: %s, call ID: %s]',
                       payload['typehint'], call_id)  # We already log the full JSON response

        typehint = payload["typehint"]
        handler = self.handlers.get(typehint)

        def feature_not_supported(m):
            msg = feedback["handler_not_implemented"]
            self.editor.raw_message(msg.format(typehint, self.launcher.ensime_version))

        if handler:
            with catch(NotImplementedError, feature_not_supported):
                handler(call_id, payload)
        else:
            self.log.warning('Response has not been handled: %s', Pretty(payload))
935598
def handle_message(self, stream, payload):
        '''
        
        '''
        try:
            payload = self.serial.loads(payload[0])
            payload = self._decode_payload(payload)
        except Exception as exc:
            exc_type = type(exc).__name__
            if exc_type == 'AuthenticationError':
                log.debug(
                    'Minion failed to auth to master. Since the payload is '
                    'encrypted, it is not known which minion failed to '
                    'authenticate. It is likely that this is a transient '
                    'failure due to the master rotating its public key.'
                )
            else:
                log.error('Bad load from minion: %s: %s', exc_type, exc)
            stream.send(self.serial.dumps('bad load'))
            raise tornado.gen.Return()

        # TODO helper functions to normalize payload?
        if not isinstance(payload, dict) or not isinstance(payload.get('load'), dict):
            log.error('payload and load must be a dict. Payload was: %s and load was %s', payload, payload.get('load'))
            stream.send(self.serial.dumps('payload and load must be a dict'))
            raise tornado.gen.Return()

        try:
            id_ = payload['load'].get('id', '')
            if str('\0') in id_:
                log.error('Payload contains an id with a null byte: %s', payload)
                stream.send(self.serial.dumps('bad load: id contains a null byte'))
                raise tornado.gen.Return()
        except TypeError:
            log.error('Payload contains non-string id: %s', payload)
            stream.send(self.serial.dumps('bad load: id {0} is not a string'.format(id_)))
            raise tornado.gen.Return()

        # intercept the "_auth" commands, since the main daemon shouldn't know
        # anything about our key auth
        if payload['enc'] == 'clear' and payload.get('load', {}).get('cmd') == '_auth':
            stream.send(self.serial.dumps(self._auth(payload['load'])))
            raise tornado.gen.Return()

        # TODO: test
        try:
            # Take the payload_handler function that was registered when we created the channel
            # and call it, returning control to the caller until it completes
            ret, req_opts = yield self.payload_handler(payload)
        except Exception as e:
            # always attempt to return an error to the minion
            stream.send(self.serial.dumps('Some exception handling minion payload'))
            log.error('Some exception handling a payload from minion', exc_info=True)
            raise tornado.gen.Return()

        req_fun = req_opts.get('fun', 'send')
        if req_fun == 'send_clear':
            stream.send(self.serial.dumps(ret))
        elif req_fun == 'send':
            stream.send(self.serial.dumps(self.crypticle.dumps(ret)))
        elif req_fun == 'send_private':
            stream.send(self.serial.dumps(self._encrypt_private(ret,
                                                                req_opts['key'],
                                                                req_opts['tgt'],
                                                                )))
        else:
            log.error('Unknown req_fun %s', req_fun)
            # always attempt to return an error to the minion
            stream.send(self.serial.dumps('Server-side exception handling payload'))
        raise tornado.gen.Return()
141976
def _deliver_errored_events(errstream, recs):
    """"""
    rlogger.info("Going to handle %s failed events", len(recs))
    rlogger.info(
        "First failed event: %s", json.dumps(recs[0], indent=4))

    kinesis_stream = errstream.get("kinesis_stream")
    randomkey = str(uuid.uuid4())
    if kinesis_stream:
        send_to_kinesis_stream(
            recs,
            kinesis_stream,
            partition_key=errstream.get("partition_key", randomkey))
        rlogger.info("Sent errors to Kinesis stream '%s'", errstream)

    delivery_stream = errstream.get("firehose_delivery_stream")
    if delivery_stream:
        send_to_delivery_stream(errevents, delivery_stream)
        rlogger.info("Sent error payload to Firehose delivery stream '%s'",
                     delivery_stream)
989912
def error_handler(f):
    """"""
    @wraps(f)
    def inner(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except NoResultFound:
            abort(404)
        except IntegrityError:
            abort(500)
    return inner
362090
def wrap_errorhandler(app):
        
        try:
            existing_handler = app.error_handler_spec[None][404][NotFound]
        except (KeyError, TypeError):
            existing_handler = None

        if existing_handler:
            app.error_handler_spec[None][404][NotFound] = \
                lambda error: handle_not_found(error, wrapped=existing_handler)
        else:
            app.error_handler_spec.setdefault(None, {}).setdefault(404, {})
            app.error_handler_spec[None][404][NotFound] = handle_not_found
938594
def _handle_processing_error(err, errstream, client):
    """"""

    errors = sorted(err.events, key=operator.attrgetter("index"))
    failed = [e.event for e in errors]
    silent = all(isinstance(e.error, OutOfOrderError) for e in errors)
    if errstream:
        _deliver_errored_events(errstream, failed)
        must_raise = False
    else:
        must_raise = True
    for _, event, error, tb in errors:
        if isinstance(error, OutOfOrderError):
            # Not really an error: do not log this to Sentry
            continue
        try:
            raise six.reraise(*tb)
        except Exception as err:
            if client:
                client.captureException()
            msg = "{}{}: {}".format(type(err).__name__,
                    err.args, json.dumps(event, indent=4))
            rlogger.error(msg, exc_info=tb)
            if must_raise:
                raise
398503
function postback(payload, callback)
{
  if (typeof payload.payload == 'string')
  {
    payload.payload = JSON.parse(payload.payload);
  }

  callback(null, payload);
}
413711
function onError(error) {
    if (error.syscall !== 'listen') throw error;

    const bind = (typeof port === 'string')
                ? 'Pipe ' + port
                : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
      case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;

      case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;

      default:
        throw error;
    }
  }
78469
function patchErrorBody(err, options) {
  // Gets the current toJSON to be extended.
  const json = err.toJSON();

  Object.keys(customOptions).forEach(optName => {
    let value = options[optName];
    if (value === undefined) {
      value = err.body[optName];
      if (value === '' || value === undefined) {
        value = customOptions[optName](
          err.body.code,
          err.statusCode,
          err.body.message
        );
      }
    }
    if (value !== undefined) {
      // Adds the option to the body of the error.
      err.body[optName] = value;
      // Adds the option to the json representation of the error.
      json[optName] = value;
    }
  });

  // Patchs the toJSON method.
  err.toJSON = () => json;
}
1084322
function (error, data) {
      const hookArgs = args.concat([ params, callback ]);

      if (error) {
        debug(`Error in REST handler: \`${error.message || error}\``);
        res.hook = hookObject(method, 'error', hookArgs);
        return next(error);
      }

      res.data = data;
      res.hook = hookObject(method, 'after', hookArgs);

      if (!data) {
        debug(`No content returned for '${req.url}'`);
        res.status(statusCodes.noContent);
      } else if (method === 'create') {
        res.status(statusCodes.created);
      }

      return next();
    }
776345
def errorhandle(self, resp):            
        """"""
        if self.format == 'json':
            parsed = xmltodict.parse(resp)
            errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN]
            # Create list of errors if more than one error response is given
            if type(errors) is list and len(errors) > 1:
                messages = ", ".join([" ".join(["{}: {}".format(k,v) for k, v in e.items()]) for e in errors])
            else:
                overlimit = any('transaction limit' in msg.lower() for msg in errors.values())
                if overlimit:
                    raise APILimitExceeded("This API key has used up its daily quota of calls.")
                else:    
                    messages = " ".join(["{}: {}".format(k,v) for k, v in errors.items()])    
        elif self.format == 'xml':
            import xml.etree.ElementTree as ET
            errors = ET.fromstring(resp).findall(self.ERROR_TOKEN)
            messages = ", ".join(err.find('msg').text for err in errors)
        else:
            raise ValueError("Invalid API response format specified: {}." % self.format)        
        
        raise BustimeError("API returned: {}".format(messages))
1066051
function sendError(error, params) {
    checkParams(params);
    
    params.status = FILE_NOT_FOUND;
    
    const data = error.message || String(error);
    
    logError(error.stack);
    
    send(data, params);
}
792151
def send(self):
        
        log = logging.getLogger(self.cls_logger + '.send')

        if self.attachments:
            self.payload['attachments'] = self.attachments

        # Encode payload in JSON
        log.debug('Using payload: %s', self.payload)
        try:
            json_payload = json.JSONEncoder().encode(self.payload)
        except(TypeError, ValueError, OverflowError):
            _, ex, trace = sys.exc_info()
            msg = 'There was a problem encoding the JSON payload\n{e}'.format(e=str(ex))
            raise OSError, msg, trace
        else:
            log.debug('JSON payload: %s', json_payload)

        # Post to Slack!
        log.debug('Posting message to Slack...')
        try:
            result = requests.post(url=self.webhook_url, data=json_payload)
        except requests.exceptions.ConnectionError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem posting to Slack\n{e}'.format(n=ex.__class__.__name__, e=str(ex))
            raise OSError, msg, trace

        # Check return code
        if result.status_code != 200:
            log.error('Slack post to url {u} failed with code: {c}'.format(c=result.status_code, u=self.webhook_url))
        else:
            log.debug('Posted message to Slack successfully.')

        # Clear out attachments after sending
        self.attachments = []
        self.payload.pop('attachments', None)
1310202
def error_handler(self, error):
        
        warnings.warn(
            """
            error_handler is deprecated.
            Use FlaskBuzz.build_error_handler instead
            """,
            warnings.DeprecationWarning,
        )
        return error.jsonify(), error.status_code, error.headers