Python process error

40 Python code examples are found related to " process error". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: vkapi.py    From vkbot with MIT License 6 votes vote down vote up
def processError(self, method, params, response):
        code = response['error']['error_code']
        if (code, method) not in self.ignored_errors and (code, '*') not in self.ignored_errors:
            logger.error('{}, params {}\ncode {}: {}'.format(method, json.dumps(params), code, response['error'].get('error_msg')))
            return False
        try:
            handler = self.ignored_errors[(code, method)]
        except KeyError:
            handler = self.ignored_errors[(code, '*')]
        if not handler:
            return False
        if params.get('_retry') or not handler[1]:
            logger.warning(retOrCall(handler[0], params, method))
            return False
        else:
            logger.warning(retOrCall(handler[0], params, method) + ', retrying')
            return True 
Example 2
Source File: __init__.py    From xrt with MIT License 6 votes vote down vote up
def processSqlError(self, query):
        sqlError = query.lastError().text()
        if len(sqlError.strip()) > 0:
            print("SQL Error!!!")
            print(query.lastQuery())
            print(sqlError)

#    def polulatePlotTemplates(self):
#
#        for ptype, pname, pvalue in zip([0, ])
#
#
#
#
#        self.query.exec_("""INSERT INTO plot_template_params (ttype, ptype, pname,
#            pvalue) VALUES (0, 0, "fluxKind", "total")""") 
Example 3
Source File: ringmasters.py    From goreviewpartner with GNU General Public License v3.0 6 votes vote down vote up
def process_error_response(self, job, message):
        """Job error response function for the job manager."""
        self.warn("game %s -- %s" % (
            job.game_id, message))
        self.void_game_count += 1
        previous_error_count = self.game_error_counts.get(job.game_id, 0)
        stop_competition, retry_game = \
            self.competition.process_game_error(job, previous_error_count)
        if retry_game and not stop_competition:
            self.games_to_replay[job.game_id] = \
                self.games_in_progress.pop(job.game_id)
            self.game_error_counts[job.game_id] = previous_error_count + 1
        else:
            del self.games_in_progress[job.game_id]
            if previous_error_count != 0:
                del self.game_error_counts[job.game_id]
        self.write_status()
        if stop_competition and not self.stopping:
            # No need to log: _halt competition will do so
            self.say('warnings', "halting run due to void games")
            self._halt_competition("too many void games") 
Example 4
Source File: kubernetes_executor.py    From airflow with Apache License 2.0 6 votes vote down vote up
def process_error(self, event: Any) -> str:
        """Process error response"""
        self.log.error(
            'Encountered Error response from k8s list namespaced pod stream => %s',
            event
        )
        raw_object = event['raw_object']
        if raw_object['code'] == 410:
            self.log.info(
                'Kubernetes resource version is too old, must reset to 0 => %s',
                (raw_object['message'],)
            )
            # Return resource version 0
            return '0'
        raise AirflowException(
            'Kubernetes failure for %s with code %s and message: %s' %
            (raw_object['reason'], raw_object['code'], raw_object['message'])
        ) 
Example 5
Source File: competitions.py    From goreviewpartner with GNU General Public License v3.0 6 votes vote down vote up
def process_game_error(self, job, previous_error_count):
        """Process a report that a job failed.

        job                  -- game_jobs.Game_job
        previous_error_count -- int >= 0

        Returns a pair of bools (stop_competition, retry_game)

        If stop_competition is True, the ringmaster will stop starting new
        games. Otherwise, if retry_game is true the ringmaster will try running
        the same game again.

        The job is one previously returned by get_game(). previous_error_count
        is the number of times that this particular job has failed before.

        Failed jobs are ones in which there was an error more serious than one
        which just causes an engine to forfeit the game. For example, the job
        will fail if one of the engines fails to respond to GTP commands at all,
        or (in particular) if it exits as soon as it's invoked because it
        doesn't like its command-line options.

        """
        raise NotImplementedError 
Example 6
Source File: core.py    From NabBot with Apache License 2.0 6 votes vote down vote up
def process_command_invoke_error(self, ctx: context.NabCtx, error: commands.CommandInvokeError):
        """Handles CommandInvokeError.

        This exception is raised when an exception is raised during command execution."""
        error_name = error.original.__class__.__name__
        if isinstance(error.original, errors.NetworkError):
            log.error(f"{error_name} in command {ctx.clean_prefix}{ctx.command.qualified_name}: {error.original}")
            return await ctx.error("I'm having network issues right now. Please try again in a moment.")
        log.error(f"{self.tag} Exception in command: {ctx.message.clean_content}", exc_info=error.original)
        if isinstance(error.original, discord.HTTPException):
            await ctx.error("Sorry, the message was too long to send.")
        else:
            if ctx.bot_permissions.embed_links:
                embed = discord.Embed(colour=discord.Colour(0xff1414))
                embed.set_author(name="Support Server", url="https://discord.gg/NmDvhpY",
                                 icon_url=self.bot.user.avatar_url)
                embed.set_footer(text="Please report this bug in the support server.")
                embed.add_field(name=f"{ctx.tick(False)}Command Error",
                                value=f"```py\n{error_name}: {error.original}```",
                                inline=False)
                await ctx.send(embed=embed)
            else:
                await ctx.error(f'Command error:\n```py\n{error_name}: {error.original}```') 
Example 7
Source File: web_xml_parser.py    From python-compat-runtime with Apache License 2.0 6 votes vote down vote up
def ProcessErrorPageNode(self, node):
    """Process error page specifications.

    If one of the supplied error codes is 404, allow fall through to runtime.

    Args:
      node: An ElementTreeNode which looks something like the following.
        <error-page>
          <error-code>500</error-code>
          <location>/errors/servererror.jsp</location>
        </error-page>
    """

    error_code = xml_parser_utils.GetChildNodeText(node, 'error-code')
    if error_code == '404':
      self.web_xml.fall_through_to_runtime = True 
Example 8
Source File: sync.py    From mlcomp with Apache License 2.0 5 votes vote down vote up
def process_error(self, e: Exception):
        if Session.sqlalchemy_error(e):
            Session.cleanup('FileSync')
            self.session = Session.create_session(key='FileSync')
            self.logger = create_logger(self.session, 'FileSync')

        hostname = socket.gethostname()
        self.logger.error(
            traceback.format_exc(), ComponentType.WorkerSupervisor,
            hostname
        ) 
Example 9
Source File: core.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def process_user_input_error(self, ctx: context.NabCtx, error: commands.UserInputError):
        """Handles UserInput errors.

        These are exceptions raised due to the user providing invalid or incorrect input."""
        if isinstance(error, commands.MissingRequiredArgument):
            await ctx.error(f"The correct syntax is: `{ctx.clean_prefix}{ctx.command.qualified_name} {ctx.usage}`.\n"
                            f"Try `{ctx.clean_prefix}help {ctx.command.qualified_name}` for more info.")
        elif isinstance(error, commands.BadArgument):
            _type, param = self.parse_bad_argument(str(error))
            # Making these errors more understandable.
            if _type == "int":
                error = f"Parameter `{param}` must be numeric."
            await ctx.error(f"{error}\nTry `{ctx.clean_prefix}help {ctx.command.qualified_name}` for more info.") 
Example 10
Source File: dump.py    From untwisted with MIT License 5 votes vote down vote up
def process_error(self, spin, excpt):
        if excpt.args[0] in SEND_ERR_CODE:
            spin.drive(SEND_ERR, excpt)
        elif excpt.args[0] in CLOSE_ERR_CODE: 
            spin.drive(CLOSE, excpt)
        else:
            raise excpt 
Example 11
Source File: app_engine_web_xml_parser.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def ProcessStaticErrorHandlersNode(self, node):
    for node in xml_parser_utils.GetNodes(node, 'handler'):
      filename = xml_parser_utils.GetAttribute(node, 'file').strip()
      error_code = xml_parser_utils.GetAttribute(node, 'error-code').strip()
      error_handler = ErrorHandler()
      error_handler.name = filename
      error_handler.code = error_code
      self.app_engine_web_xml.static_error_handlers.append(error_handler) 
Example 12
Source File: streambase.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def process_stream_error(self, error):
        """Process stream error element received.

        :Parameters:
            - `error`: error received

        :Types:
            - `error`: `StreamErrorElement`
        """
        # pylint: disable-msg=R0201
        logger.debug("Unhandled stream error: condition: {0} {1!r}"
                            .format(error.condition_name, error.serialize())) 
Example 13
Source File: parinfer.py    From sublime-text-parinfer with ISC License 5 votes vote down vote up
def processError(result, e):
    result.success = False
    if 'parinferError' in e:
        del e['parinferError']
        result.error = e
    else:
        result.error.name = ERROR_UNHANDLED
        result.error.message = e.stack
        raise e 
Example 14
Source File: user_stream.py    From python-api with Apache License 2.0 5 votes vote down vote up
def process_error(self, message_wrapper):
    # error_code == maintenance accompanies exchange engine going down for maintenance which
    # causes graceful disconnect of the WebSocket, handled by MarketStreamListener.on_disconnect
    if message_wrapper['error_code'] != 'maintenance':
      self.on_error(Exception('WebSocket error: ' + message_wrapper['error_code'])) 
Example 15
Source File: oauth.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def process_error(self, data):
        if 'oauth_problem' in data:
            if data['oauth_problem'] == 'user_refused':
                raise AuthCanceled(self, 'User refused the access')
            raise AuthUnknownError(self, 'Error was ' + data['oauth_problem']) 
Example 16
Source File: KVADefault.py    From stonix with GNU General Public License v2.0 5 votes vote down vote up
def processError(self, error, errorstring, innerlist, templist1, key):
        self.logger.log(LogPriority.DEBUG, "there is an error!")
        '''the command run doesn't return a valid value, key may
        not exist or may have had an error running the command'''
        cmdlist = []
        '''check if the output contains a does not exist message'''
        if re.search("does not exist", errorstring):
            '''If the value of the innerlist that developer passed in is None,
            then that is ok, we didn't want/expect it to exist'''
            if innerlist[1] is None:
                self.nocmd = True
                return True
            else:
                if templist1:
                    if self.currentHost:
                        write = [self.dc, self.host, "write", self.path, key]
                    else:
                        write = [self.dc, "write", self.path, key]
                    for item in templist1:
                        write.append(item)
                else:
                    if self.currentHost:
                        write = self.dc + " " + self.host + \
                            " write " + self.path + " " + key + \
                            innerlist[1]
                    else:
                        write = self.dc + " write " + self.path + \
                            " " + key + " " + innerlist[1]
                if self.currentHost:
                    undo = [self.dc, self.host, "delete", self.path, key]
                else:
                    undo = [self.dc, "delete", self.path, key]
        else:
            '''There was some other error, could be a bad command'''
            msg = "There was some error running defaults read command"
            raise OSError(msg)
        cmdlist.append(write)
        cmdlist.append(undo)
        return cmdlist
############################################################################### 
Example 17
Source File: batch_rvt_monitor_util.py    From RevitBatchProcessor with GNU General Public License v3.0 5 votes vote down vote up
def ShowRevitProcessError(processErrorStream, showRevitProcessErrorMessages, output, pendingReadLineTask=None):
    outputLines, pendingReadLineTask = stream_io_util.ReadAvailableLines(processErrorStream, pendingReadLineTask)
    if outputLines.Any():
        for line in outputLines:
            if line.StartsWith("log4cplus:"): # ignore pesky log4cplus messages (an Autodesk thing?)
                pass
            elif showRevitProcessErrorMessages:
                output("\t" + "- [ REVIT ERROR MESSAGE ] : " + line)
    return pendingReadLineTask 
Example 18
Source File: msbuild.py    From RevitBatchProcessor with GNU General Public License v3.0 5 votes vote down vote up
def ProcessError(errorLine):
  previousColor = Console.ForegroundColor
  Console.ForegroundColor = ConsoleColor.Red
  print "  " + errorLine
  Console.ForegroundColor = previousColor
  return 
Example 19
Source File: get_process_output.py    From RevitBatchProcessor with GNU General Public License v3.0 5 votes vote down vote up
def ReadProcessOutputAndErrorLines(process, processOutput, processError, timeOutInMs=-1):
  completed = False
  outputData = StreamData(process.StandardOutput)
  errorData = StreamData(process.StandardError)
  task2stream = Dictionary[Task, StreamData]()
  task2stream[outputData.GetStream().ReadLineAsync()] = outputData
  task2stream[errorData.GetStream().ReadLineAsync()] = errorData
  while True:
    tasks = task2stream.Keys.ToArray[Task]()
    index = Task.WaitAny(tasks, timeOutInMs)
    if index == -1: # timed out!
      completed = False
      break
    task = tasks[index]
    line = task.Result
    streamData = task2stream[task]
    task2stream.Remove(task) # must remove the completed task.
    if line is not None:
      streamData.AddLine(line)
      if streamData == outputData:
        processOutput(line)
      elif streamData == errorData:
        processError(line)
      else:
        raise Exception("Unexpected program state!")
      task2stream[streamData.GetStream().ReadLineAsync()] = streamData

    if not task2stream.Any():
      completed = True
      break
  return outputData.GetLines(), errorData.GetLines(), completed 
Example 20
Source File: views.py    From donate-wagtail with Mozilla Public License 2.0 5 votes vote down vote up
def process_braintree_error_result(self, result, form):
        """
        Parse an error result object from Braintree, and look for errors
        that we can report back to the user. If we find any, add these to the
        form.
        """
        default_error_message = _('Sorry there was an error processing your payment. '
                                  'Please try again later or use a different payment method.')

        if result.errors.deep_errors:
            # Validation errors exist - check if they are meaningful to the user
            try:
                self.check_for_address_errors(result)
            except InvalidAddress as e:
                self.gateway_address_errors = e.errors
                return self.form_invalid(form)

            errors_to_report = self.filter_user_card_errors(result)
            if errors_to_report:
                for error_msg in errors_to_report:
                    form.add_error(None, error_msg)
            else:
                form.add_error(None, default_error_message)
        else:
            # Processor decline or some other exception
            form.add_error(None, default_error_message)

        queue_ga_event(self.request, ['send', 'event', {
                'eventCategory': 'User Flow',
                'eventAction': 'Card Error',
                'eventLabel': result.message,
            }
        ])
        return self.form_invalid(form) 
Example 21
Source File: layer.py    From ueberzug with GNU General Public License v3.0 5 votes vote down vote up
def process_error(parser, exception):
    print(parser.unparse({
        'type': 'error',
        'name': type(exception).__name__,
        'message': str(exception),
        # 'stack': traceback.format_exc()
    }), file=sys.stderr) 
Example 22
Source File: console.py    From screeps-stats with MIT License 5 votes vote down vote up
def process_error(self, ws, message):
        body = {
            'timestamp': datetime.now(),
            'message': message,
            'mtype': 'error',
            'severity': 5
        }
        res = self.es.index(index="screeps-console-" + time.strftime("%Y_%m"), doc_type="log", body=body) 
Example 23
Source File: letters_pdf_tasks.py    From notifications-api with MIT License 5 votes vote down vote up
def process_virus_scan_error(filename):
    move_failed_pdf(filename, ScanErrorType.ERROR)
    reference = get_reference_from_filename(filename)
    notification = dao_get_notification_by_reference(reference)
    updated_count = update_letter_pdf_status(reference, NOTIFICATION_TECHNICAL_FAILURE, billable_units=0)

    if updated_count != 1:
        raise Exception(
            "There should only be one letter notification for each reference. Found {} notifications".format(
                updated_count
            )
        )
    error = VirusScanError('notification id {} Virus scan error: {}'.format(notification.id, filename))
    current_app.logger.exception(error)
    raise error 
Example 24
Source File: eventhub_streaming_client.py    From agogosml with MIT License 5 votes vote down vote up
def process_error_async(self, context, error):  # pragma: no cover
        """
        Recover from an error.

        Called when the underlying client experiences an error while receiving.
        EventProcessorHost will take care of continuing to pump messages, so
        no external action is required.

        :param context: Information about the partition.
        :type context: ~azure.eventprocessorhost.PartitionContext
        :param error: The error that occured.
        """
        self.logger.error("Event Processor Error %s", error) 
Example 25
Source File: fleetWindow.py    From PyEveLiveDPS with GNU General Public License v3.0 5 votes vote down vote up
def processErrorQueue(self, errorQueue):
        while not errorQueue.empty():
            error = errorQueue.get(False)
            if error == 'Character is not in a fleet':
                self.topLabel['text'] = "Fleet Stats (You are not in a fleet)" 
Example 26
Source File: hidsrv9.py    From P4wnP1 with GNU General Public License v3.0 5 votes vote down vote up
def process_bash_error(qout, subproc):
	buf = ""
	while True:
		bash = subproc[0]
		errstream = bash.stderr

		# check for output which needs to be delivered from backing bash stderr
		try:
			r,w,ex = select([errstream], [], [], 0.1)
		except ValueError:
			# we should land here if the error stream is closed
			# because a new bash process was started
			pass
		
		if errstream in r:
			byte = errstream.read(1)
			if byte == "\n":
				# full line received from subprocess, send it to HID
				#   note: the newline char isn't send, as each outputstream is printed in a separate line by the powershell client
			
				# dst = 3 (stderr of client)
				send_datastream(qout, 3, 3, buf)
				# clear buffer
				buf = ""
			else:
				buf += byte

# As we don't pipe CTRL+C intterupt from client through
# HID data stream, there has to be another option to reset the bash process if it stalls
# This could easily happen, as we don't support interactive commands, waiting for input
# (this non-interactive shell restriction should be a known hurdle to every pentester out there) 
Example 27
Source File: texoutparse.py    From textext with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def process_error(self, match):
        """
        Process a warning regex match and return the log message object.

        :param match: regex match object to process
        :return: LogFileMessage object
        """

        # Regex match groups
        # 0 - Whole match (line)
        # 1 - Type (LaTeX|Package|Class)
        # 2 - Package or Class (\w+)
        # 3 - extra (\(([\\]\w+)\))
        # 4 - Error message for typed error (.*)
        # 5 - TeX error message (.*)

        message = LogFileMessage()
        if match.group(1) is not None:
            message['type'] = type_ = match.group(1)

            if type_ == 'Package':
                # Package name should be group 2
                message['package'] = match.group(2)
            elif type_ == 'Class':
                # Class name should be group 2
                message['class'] = match.group(2)
            elif match.group(2) is not None:
                message['component'] = match.group(2)

            if match.group(3) is not None:
                message['extra'] = match.group(3)

            message['message'] = match.group(4)
        else:
            message['message'] = match.group(5)

        self.errors.append(message)
        return message 
Example 28
Source File: errors.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def process_store_error(cpe, program):
    message = cpe.output.decode('utf-8')
    if 'credentials not found in native keychain' in message:
        return CredentialsNotFound(
            'No matching credentials in {0}'.format(
                program
            )
        )
    return StoreError(
        'Credentials store {0} exited with "{1}".'.format(
            program, cpe.output.decode('utf-8').strip()
        )
    ) 
Example 29
Source File: views.py    From openvpn-admin-ui with Apache License 2.0 5 votes vote down vote up
def process_error():
    url = current_app.config['SCHEDULER_ERROR'];
    if os.path.exists(url):
        respnse = make_response(send_file(url))
        respnse.headers["Content-Disposition"] = "attament; filename=scheduler.error"
        return respnse
    else:
        flash('Log file does not exist', 'danger')
        return render_template('status.html') 
Example 30
Source File: eph.py    From azure-event-hubs-python with MIT License 5 votes vote down vote up
def process_error_async(self, context, error):
        """
        Called when the underlying client experiences an error while receiving.
        EventProcessorHost will take care of recovering from the error and
        continuing to pump messages,so no action is required from
        :param context: Information about the partition
        :type context: ~azure.eventprocessorhost.PartitionContext
        :param error: The error that occured.
        """
        logger.error("Event Processor Error {!r}".format(error)) 
Example 31
Source File: processes.py    From crontabs with MIT License 5 votes vote down vote up
def process_error_queue(self, error_queue):
        try:
            error_name = error_queue.get(timeout=self.TIMEOUT_SECONDS)
            if error_name:
                error_name = error_name.strip()
                self._subprocesses = [s for s in self._subprocesses if s._name != error_name]
                logger = daiquiri.getLogger(error_name)
                logger.info('Will not auto-restart because it\'s not robust')

        except Empty:
            pass 
Example 32
Source File: hsportscanner.py    From hsportscanner with MIT License 5 votes vote down vote up
def process_soccks5_error(hid_serv,port_ndx,e):
    hostname = hid_serv.onion_address
    port = hid_serv.ports_to_scan[port_ndx]
    if e.value[0] == SOCKS_DESC_UNAVAILABLE:
        hid_serv.connect_state = CONN_STATE_DESC_UNAVAILABLE
        #hid_serv.failed_connect_tries += 1
        thdprint(LOG_NOTICE,"{0}:{1} DESC_UNAVAILABLE/NO_INTROS; {2}".format(hostname,port,e.value))

    elif e.value[0] == SOCKS_CANT_ATTACH or e.value[0] == SOCKS_TTL_EXPIRED:
        hid_serv.connect_state = CONN_STATE_TIMEDOUT
        #hid_serv.failed_connect_tries += 1
        thdprint(LOG_INFO,"{0}:{1} CANT_ATTACH/TTL_EXPIRED; {2}".format(hostname,port,e.value))

    elif (e.value[0] in [SOCKS_REFUSED_CONN_BY_RULE,SOCKS_REFUSED_CONN_REMOTE]): # means we connected and the port is closed
        hid_serv.failed_connect_tries = 0  # reset failed tried counter
	if port_ndx >= hid_serv.next_port_ndx_to_scan:
            hid_serv.next_port_ndx_to_scan = (port_ndx+1)
        hid_serv.connect_state = CONN_STATE_CONNECTED
        thdprint(LOG_INFO,"{0}:{1} DESC_HERE/PORT_CLOSED {2}".format(hostname,port,e.value))

    elif (e.value[0] == SOCKS_TOR_MISC): # also means that we connected.
        hid_serv.failed_connect_tries = 0  # reset failed tried counter
	if port_ndx >= hid_serv.next_port_ndx_to_scan:
            hid_serv.next_port_ndx_to_scan = (port_ndx+1)
        hid_serv.connect_state = CONN_STATE_CONNECTED
        thdprint(LOG_INFO,"{0}:{1} DESC_HERE/PORT_FILTERED {2}".format(hostname,port,e.value))

    else: # means that we downloaded the desc and tried to establish rend and intro circuit
        hid_serv.connect_state = CONN_STATE_FAILED_REASON_UNKNOWN
        #hid_serv.failed_connect_tries += 1
        thdprint(LOG_INFO,"{0}:{1} CONN_FAILED/UKNOWN_REASON {2}".format(hostname,port,e.value))
    return 0

## Run wget for for onion address in case --crawl-open-ports was specified in the command line.
#  See wget paramters at the beginning of this file
# 
#  @param port Make wget to connect to this port
#  @return 0 
Example 33
Source File: get_campaigns_by_label.py    From google-ads-python with Apache License 2.0 5 votes vote down vote up
def print_error_and_exit_process(error):
    """Prints the details of a GoogleAdsException and exits the current process.

    Args:
        error: An instance of a GoogleAdsException.
    """
    print('Request with ID "{}" failed with status "{}" and includes the '
          'following errors:'.format(error.request_id, error.error.code().name))
    for error in error.failure.errors:
        print('\tError with message "{}".'.format(error.message))
        if error.location:
            for field_path_element in error.location.field_path_elements:
                print('\t\tOn field: {}'.format(
                    field_path_element.field_name))
    sys.exit(1) 
Example 34
Source File: listeners.py    From pyiqfeed with GNU General Public License v2.0 5 votes vote down vote up
def process_error(self, fields):
        """Called with an error message"""
        pass


# noinspection PyMethodMayBeStatic 
Example 35
Source File: preprocess.py    From pytci with MIT License 5 votes vote down vote up
def process_error(state, position):
    macro_stream = state.macro_stream()
    if state.processing:
        message = ' '.join(map(value_of, macro_stream))
        return [tokenize.token(position, 'error', message)]
    return () 
Example 36
Source File: gbq.py    From pandas-gbq with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def process_http_error(ex):
        # See `BigQuery Troubleshooting Errors
        # <https://cloud.google.com/bigquery/troubleshooting-errors>`__

        raise GenericGBQException("Reason: {0}".format(ex)) 
Example 37
Source File: applepush.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def processError(self, status, identifier):
        """
        Handles an error message we've received on the provider channel.
        If the error code is one that indicates a bad token, remove all
        subscriptions corresponding to that token.

        @param status: The status value returned from APN Feedback server
        @type status: C{int}

        @param identifier: The identifier of the outbound push notification
            message which had a problem.
        @type status: C{int}
        """
        msg = self.STATUS_CODES.get(status, "Unknown status code")
        self.log.info("Received APN error {status} on identifier {id}: {msg}", status=status, id=identifier, msg=msg)
        if status in self.TOKEN_REMOVAL_CODES:
            token = self.history.extractIdentifier(identifier)
            if token is not None:
                self.log.debug(
                    "Removing subscriptions for bad token: {token}",
                    token=token,
                )
                txn = self.factory.store.newTransaction(label="APNProviderProtocol.processError")
                subscriptions = (yield txn.apnSubscriptionsByToken(token))
                for record in subscriptions:
                    self.log.debug(
                        "Removing subscription: {token} {key}",
                        token=token, key=record.resourceKey
                    )
                    yield txn.removeAPNSubscription(token, record.resourceKey)
                yield txn.commit() 
Example 38
Source File: s3stat.py    From s3stat with MIT License 5 votes vote down vote up
def process_error(self, exc, data=None):
        """
        This is the error handling method to be overwritten by implementers.

        :param exc: the exception object raised and catched somewhere during processing
        :param data: an optional attribute that might help further processing
        :returns: the returned value will be returned from the main `run` method.
        """
        print data
        raise exc 
Example 39
Source File: worker.py    From docassemble with MIT License 4 votes vote down vote up
def process_error(interview, session_code, yaml_filename, secret, user_info, url, url_root, is_encrypted, error_type, error_message, error_trace, variables, extra):
    start_time = time.time()
    new_action = worker_controller.functions.this_thread.current_info['on_error']
    new_action['arguments']['error_type'] = error_type
    new_action['arguments']['error_message'] = error_message
    new_action['arguments']['error_trace'] = error_trace
    new_action['arguments']['variables'] = variables
    worker_controller.obtain_lock(session_code, yaml_filename)
    steps, user_dict, is_encrypted = worker_controller.fetch_user_dict(session_code, yaml_filename, secret=secret)
    interview_status = worker_controller.parse.InterviewStatus(current_info=dict(user=user_info, session=session_code, secret=secret, yaml_filename=yaml_filename, url=url, url_root=url_root, encrypted=is_encrypted, interface='worker', action=new_action['action'], arguments=new_action['arguments']))
    old_language = worker_controller.functions.get_language()
    try:
        interview.assemble(user_dict, interview_status)
    except Exception as e:
        if hasattr(e, 'traceback'):
            sys.stderr.write("Error in assembly during error callback: " + str(e.__class__.__name__) + ": " + str(e) + ": " + str(e.traceback))
        else:
            sys.stderr.write("Error in assembly during error callback: " + str(e.__class__.__name__) + ": " + str(e))
        error_type = e.__class__.__name__
        error_message = str(e)
        if hasattr(e, 'traceback'):
            error_trace = str(e.traceback)
            if hasattr(e, 'da_line_with_error'):
                error_trace += "\nIn line: " + str(e.da_line_with_error)
        else:
            error_trace = None
        worker_controller.error_notification(e, message=error_message, trace=error_trace)
    worker_controller.functions.set_language(old_language)
    # is this right?
    save_status = worker_controller.functions.this_thread.misc.get('save_status', 'new')
    if save_status != 'ignore':
        if str(user_info.get('the_user_id', None)).startswith('t'):
            worker_controller.save_user_dict(session_code, user_dict, yaml_filename, secret=secret, encrypt=is_encrypted, steps=steps)
        else:
            worker_controller.save_user_dict(session_code, user_dict, yaml_filename, secret=secret, encrypt=is_encrypted, manual_user_id=user_info['theid'], steps=steps)
    worker_controller.release_lock(session_code, yaml_filename)
    if hasattr(interview_status, 'question'):
        if interview_status.question.question_type == "response":
            sys.stderr.write("Time in error callback was " + str(time.time() - start_time) + "\n")
            #sys.stderr.write("background_action: status in error callback was response\n")
            if hasattr(interview_status.question, 'all_variables'):
                pass
            elif not hasattr(interview_status.question, 'binaryresponse'):
                sys.stdout.write(interview_status.questionText.rstrip().encode('utf8') + "\n")
        elif interview_status.question.question_type == "backgroundresponse":
            sys.stderr.write("Time in error callback was " + str(time.time() - start_time) + "\n")
            return worker_controller.functions.ReturnValue(ok=False, error_type=error_type, error_trace=error_trace, error_message=error_message, variables=variables, value=interview_status.question.backgroundresponse, extra=extra)
    sys.stderr.write("Time in error callback was " + str(time.time() - start_time) + "\n")
    return worker_controller.functions.ReturnValue(ok=False, error_type=error_type, error_trace=error_trace, error_message=error_message, variables=variables, extra=extra) 
Example 40
Source File: app.py    From PythonBuddy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def process_error(error):
    """Formats error message into dictionary

        :param error: pylint error full text
        :return: dictionary of error as:
            {
                "code":...,
                "error": ...,
                "message": ...,
                "line": ...,
                "error_info": ...,
            }
    """
    # Return None if not an error or warning
    if error == " " or error is None:
        return None
    if error.find("Your code has been rated at") > -1:
        return None

    list_words = error.split()
    if len(list_words) < 3:
        return None

    # Detect OS
    line_num = None
    if is_os_linux():
        try:
            line_num = error.split(":")[1]
        except Exception as e:
            print(os.name + " not compatible: " + e)
    else:
        line_num = error.split(":")[2]

    # list_words.pop(0)
    error_yet, message_yet, first_time = False, False, True
    i, length = 0, len(list_words)
    # error_code=None
    while i < length:
        word = list_words[i]
        if (word == "error" or word == "warning") and first_time:
            error_yet = True
            first_time = False
            i += 1
            continue
        if error_yet:
            error_code = word[1:-1]
            error_string = list_words[i + 1][:-1]
            i = i + 3
            error_yet = False
            message_yet = True
            continue
        if message_yet:
            full_message = ' '.join(list_words[i:length - 1])
            break
        i += 1

    error_info = pylint_dict_final[error_code]

    return {
        "code": error_code,
        "error": error_string,
        "message": full_message,
        "line": line_num,
        "error_info": error_info,
    }