def errback(failure): try: if failure.check(ServerMessage): self.root.runCallback('msg', failure.getErrorMessage()) else: self.root.runCallback('debug', failure.getErrorMessage()) self.root._failure() finally: self._startCall()
def on_failure(self, failure, request): """ Handle exceptions raised during RestResource processing :param failure: ``twisted.python.failure.Failure`` instance :param request: ``twisted.web.server.Request`` instance """ fq_name = self.__module__ + '.' + self.__class__.__name__ file_path = abspath(inspect.getfile(self.__class__)) if failure.check(CancelledError): # the request / deferred chain has been cancelled early. # doesn't matter if we respond no one is listening. rstr = err = 'Request was cancelled' elif failure.check(_DefGen_Return): failure.printBriefTraceback() err = dedent(''' Received a Deferred Generator Response from Resource (%s) in the method: [%s] .................................... This indicates you may be missing a yield statement and the decorator `@defer.inlineCallbacks`. File: %s If you do not have a yield statement, you should use a regular `return` statement and remove `defer.returnValue()` ''' % (fq_name, request.method_called, file_path)).strip() log.err(err + ' - ' + failure.getErrorMessage()) rstr = self.ERROR_CLASS( INTERNAL_SERVER_ERROR, err, failure.getErrorMessage(), is_logged=False ).render(request) else: log.err('Exception in Resource (%s) [%s] <%s> - %s' % ( fq_name, request.method_called, file_path, failure.getErrorMessage())) failure.printTraceback() rstr = self.ERROR_CLASS( INTERNAL_SERVER_ERROR, 'Unhandled Error', 'Exception in Resource (%s) [%s] <%s> - %s' % ( fq_name, request.method_called, file_path, failure.getTraceback()), is_logged=False ).render(request) if request.finished: return request.write(rstr) request.finish()
def failed(failure): print 'download failed for ', str(url) if failure.getErrorMessage() in ['Connection was closed cleanly.', 'User timeout caused connection failure.', ]: retries = self.img_fetch_count.get(str(url), 0) if retries <= self.img_max_retries: print 'retrying download! (%d)' % retries self._download_image(url, title) else: print 'skipping img, max retry count reached' else: print 'unknown download error:', failure.getErrorMessage() print failure
def errback(failure): try: if failure.check(ServerMessage): self.root.runCallback('msg', failure.getErrorMessage()) self.root._failure() finally: self._startCall()
def report_error(failure, line_fun=None, include_stacktrace=True): if line_fun is None: def line_fun(line): logger.debug(line) if isinstance(failure, SshFailure): return failure if hasattr(failure.value, 'component'): line_fun('%s%s: %s' % (_determine_issued_command(failure), failure.value.component, failure.getErrorMessage())) else: line_fun(failure.getErrorMessage()) if include_stacktrace: for line in failure.getBriefTraceback().splitlines(): line_fun(line) return failure
def errorCbk(self, failure, args): ''' Errback for error in operator detection http ''' request = args['request'] request.write(self.exceptionToJson(request, failure.getErrorMessage())) request.finish()
def errback(failure): if not self.currentlyAsking: return self.currentlyAsking = False if failure.check(ServerMessage): self.root.runCallback('msg', failure.getErrorMessage()) self.root._failure() self._startCall()
def printError(self, failure, request): """Imprime el error de failure y genera una fila vacia para la consulta de la base de datos """ session = request.getSession() d = defer.maybeDeferred(lambda :None) d.addCallback(lambda a: request.write("""<div class="error"> %s </div>""" % \ failure.getErrorMessage())) d.addCallback(self.getEmptyRow, 2) return d
def _formatFailure(failure): res = errorTemplate%( "<h1>Internal Error</h1><p>A(n)" " %s exception occurred. The" " accompanying message is: '%s'</p>" "<p>If you are seeing this, it is always a bug in our code" " or the data descriptions, and we would be extremely grateful" " for a report at" " %s</p>"%(failure.value.__class__.__name__, common.escapeForHTML(failure.getErrorMessage()),config.getMeta("contact.email").getContent())) return res.encode("ascii", "ignore")
def parseEb(failure): self.debug("parse: eb: failure: %r\n%s\n", failure.getErrorMessage(), failure.getTraceback()) # we can get here even before we run the reactor below; # so schedule a stop instead of doing it here # self.reactor.stop() self.reactor.callLater(0, self.reactor.stop) if failure.check(command.CommandExited): self.stderr.write(failure.value.output + "\n") reason = failure.value.status self.returnValue = reason return reason self.warning("errback: %r", failure.getErrorMessage()) self.stderr.write("Failure: %s\n" % failure.value) self.returnValue = failure # we handled it by storing it for reraising, so don't # return it return
def parseEb(failure): self.debug('parse: eb: failure: %r\n%s\n', failure.getErrorMessage(), failure.getTraceback()) # we can get here even before we run the reactor below; # so schedule a stop instead of doing it here # self.reactor.stop() self.reactor.callLater(0, self.reactor.stop) if failure.check(command.CommandExited): self.stderr.write(failure.value.output + '\n') reason = failure.value.status self.returnValue = reason return reason self.warning('errback: %r', failure.getErrorMessage()) self.stderr.write('Failure: %s\n' % failure.value) self.returnValue = failure # we handled it by storing it for reraising, so don't # return it return
def report_error(failure, line_fun=None, include_stacktrace=False): if getattr(failure, "handled", False): return failure failure.handled = True if line_fun is None: def line_fun(line): logger.debug(line) if isinstance(failure, SshFailure): return failure if hasattr(failure.value, 'component'): line_fun('%s%s: %s' % (_determine_issued_command(failure), failure.value.component, failure.getErrorMessage())) else: line_fun(failure.getErrorMessage()) logger.debug(failure.getTraceback()) if include_stacktrace: for line in failure.getBriefTraceback().splitlines(): line_fun(line) return failure
def _error_handler(self, failure): exception = failure.value msg = failure.getErrorMessage() if isinstance(exception, web_error.Error): status = int(exception.status) if status == 409: raise ConflictError(msg) elif status == 404: raise NotFoundError(msg) else: self.info(exception.response) raise NotImplementedError("Behaviour for response code %d not define yet, FIXME!" % status) elif failure.check(error.ConnectionRefusedError): self._on_disconnected() self.reconnect() raise NotConnectedError("Database connection refused.") else: failure.raiseException()
def unexpectedError(self, failure): request = errorlog.ScriptRequest([ ('branch_id', self.branch_id), ('source', self.source_url), ('dest', self.destination_url), ('error-explanation', failure.getErrorMessage())]) request.URL = get_canonical_url_for_branch_name(self.unique_name) # If the sub-process exited abnormally, the stderr it produced is # probably a much more interesting traceback than the one attached to # the Failure we've been passed. tb = None if failure.check(error.ProcessTerminated, UnexpectedStderr): tb = getattr(failure, 'error', None) if tb is None: tb = failure.getTraceback() errorlog.globalErrorUtility.raising( (failure.type, failure.value, tb), request) self.logger.info('Recorded %s', request.oopsid)
def unexpectedError(self, failure): request = errorlog.ScriptRequest([('branch_id', self.branch_id), ('source', self.source_url), ('dest', self.destination_url), ('error-explanation', failure.getErrorMessage())]) request.URL = get_canonical_url_for_branch_name(self.unique_name) # If the sub-process exited abnormally, the stderr it produced is # probably a much more interesting traceback than the one attached to # the Failure we've been passed. tb = None if failure.check(error.ProcessTerminated, UnexpectedStderr): tb = getattr(failure, 'error', None) if tb is None: tb = failure.getTraceback() errorlog.globalErrorUtility.raising((failure.type, failure.value, tb), request) self.logger.info('Recorded %s', request.oopsid)
def _error_handler(self, failure, tag=None): exception = failure.value msg = failure.getErrorMessage() if isinstance(exception, web_error.Error): prefix = (tag + " ") if tag is not None else "" status = int(exception.status) if status == 409: raise ConflictError("%s%s" % (prefix, msg)) elif status == 404: raise NotFoundError("%s%s" % (prefix, msg)) else: self.error('%s%s' % (prefix, exception.response)) raise NotImplementedError( 'Behaviour for response code %d not defined yet, FIXME!' % status) elif failure.check(error.ConnectionRefusedError): self._on_disconnected() self.reconnect() raise NotConnectedError("Database connection refused.") else: failure.raiseException()
def handle_error(failure=None, **kw): # It gets really confusing if we raise an exception from this # method (the branch remains locked, but this isn't obvious to # the client). We could just log the failure using Twisted's # log.err but this results in text containing traceback # information etc being written to stderr. Since stderr is # displayed to the user, if for example they arrive at this point # via the smart server, we want to ensure that the message is # sanitised. So what we will do is raise an oops and ask the user # to log a bug with the oops information. # See bugs 674305 and 675517 for details. request = errorlog.ScriptRequest( [("source", virtual_url_fragment), ("error-explanation", failure.getErrorMessage())] ) self.unexpectedError(failure, request) fault = faults.OopsOccurred("updating a Launchpad branch", request.oopsid) # Twisted's log.err used to write to stderr but it doesn't now so # we will write to stderr as well as log.err. print >>sys.stderr, repr(fault) log.err(repr(fault)) return fault
def handle_error(failure=None, **kw): # It gets really confusing if we raise an exception from this # method (the branch remains locked, but this isn't obvious to # the client). We could just log the failure using Twisted's # log.err but this results in text containing traceback # information etc being written to stderr. Since stderr is # displayed to the user, if for example they arrive at this point # via the smart server, we want to ensure that the message is # sanitised. So what we will do is raise an oops and ask the user # to log a bug with the oops information. # See bugs 674305 and 675517 for details. request = errorlog.ScriptRequest([('source', virtual_url_fragment), ('error-explanation', failure.getErrorMessage())]) self.unexpectedError(failure, request) fault = faults.OopsOccurred("updating a Launchpad branch", request.oopsid) # Twisted's log.err used to write to stderr but it doesn't now so # we will write to stderr as well as log.err. print >> sys.stderr, repr(fault) log.err(repr(fault)) return fault
def __checkJobStepResults(self, failure, status): "Check that given self.js.status is set to correct value after certain JobStep operation" twisted_logger.writeLog(self.logPrefix, None, "Checking test results...") if failure is not None: error = failure.getErrorMessage() failure.trap(RuntimeError) print "ERROR: %s" % error else: error = None query = "select status, text_input, error, start_time, end_time from scs.job_step " \ "where job_id = %d and step_id = %d" % (self.js.jobID, self.js.stepID) res = synchdb.query(query) db_status, text_input, db_error, start_time, end_time = res[0] self.assertEquals(str(self.js.input), text_input, "<scs.job_step> text_input ('%s') not equals to expected input ('%s')" % (text_input, str(self.js.input))) self.assertEquals(error, db_error, "<scs.job_step> error ('%s') not equals to expected error ('%s')" % (db_error, error)) self.assertEquals(status, db_status, "<scs.job_step> status ('%s') not equals to expected status ('%s')" % (db_status, status)) self.assertEquals(self.js.status, status, "<js.status> ('%s') not equals to expected status ('%s')" % (self.js.status, status)) if self.js.status != 'RUNNING': self.assertNotEquals(end_time, None) twisted_logger.writeLog(self.logPrefix, None, "Test succeeded!")
def error(self, failure, op=""): if failure.type == pb.PBConnectionLost: return serverLog.warn('Error in %s: %s' % (op, str(failure.getErrorMessage())))
def __init__(self, database_configuration): self.database_configuration = database_configuration for key in ('database_name', 'user', 'password'): setattr(self, key, database_configuration.get(key)) # Options for which we'll provide a default: for key, default in (('protocol', 'postgresql'), ('pool_size', 10), ('timeout', 1), ('reconnect_wait', 10), ('host', '')): # The empty string as a host means use local socket setattr(self, key, database_configuration.get(key, default)) if not self.protocol in ('postgresql', 'mysql'): raise ValueError('The provider currently only works with PostgreSQL and MySQL, not ' + self.protocol) # Options to provide to the underlying DBAPI-driver. self.dbapi_options = database_configuration.get('dbapi_options', {}) self.is_connected = False self.engine = None self.port = None # The default port is set by _configure_(postgres|mysql) self.on_connection_established = event.Event() #: Event called when a connection has been established. Provides a metadata instance as argument. self.on_connection_lost = event.Event() self.on_connection_failed = event.Event() log_failure = lambda failure: log.error('A connection to "%s" failed: %s' % (self.database_name, failure.getErrorMessage())) self.on_connection_failed += log_failure self.on_connection_failed += lambda failure: self.keep_reconnecting_and_report() self._reconnect_deferred = None self._should_reflect = False self._has_reflected = False self.metadata = None self.metadata_factory = sa.MetaData
def printError(self, failure): """Imprime el error de failure""" print failure.getErrorMessage()
def _error(self, failure): print failure.getErrorMessage() return self._reconnect()
def downloadError(self, failure): self.downloaded = False self.running = False print "Error:", failure.getErrorMessage() self.__finishCB(None)
def _fail(failure): print "Discovery result:", failure.getErrorMessage() d.errback(failure) return failure
def _loginFailed(self, failure): self.transport.write("Denied: %s.\r\n" % failure.getErrorMessage()) self.transport.loseConnection()
def fetch_torrent_failure(self, failure): self.download.status = Status.FAILED self.download.status_message = unicode(failure.getErrorMessage()) if 'state_changed_alert' in self.dfm: self.dfm['state_changed_alert'].errback(failure) del self.dfm['state_changed_alert']
def fail(failure): """ Error in NTCP""" print 'ERROR in NTCP (get configuration):', failure.getErrorMessage() return None
def _kStoreErr(self, failure, host, port): logger.info("couldn't store on %s:%d -- %s" % (host, port, failure.getErrorMessage())) print "_kStoreErr was: %s" % failure # XXX: updateNode-- return failure
def error(failure): print('Failure!: %s' % failure.getErrorMessage()) reactor.stop()
def fail(failure): print "STUNT failed:", failure.getErrorMessage()
def _stopFailureHandler(self, failure): "Server termination failure handler" err_msg = "'%s' server shutdown failure: %s" % (self.name, failure.getErrorMessage()) twisted_logger.writeErr(self.logPrefix, self.logName, err_msg)
def errkfindnode(self, failure, key, host, port, raiseException=True): logger.info("kFindNode %s request to %s:%d failed -- %s" % (self.abbrv, host, port, failure.getErrorMessage())) # XXX: updateNode-- if raiseException: return failure
def _unresolved(failure): print failure.getErrorMessage()
def _error(failure): log.msg('There was an error: ' + failure.getErrorMessage()) _ensureReactorStop()
def _showError(self, failure): return failure.getErrorMessage()
def findHash_error(self, failure, req, url, orig_resp, d): """Process the error in hash lookup by returning an empty L{HashObject}.""" log.msg('Hash lookup for %s resulted in an error: %s' % (url, failure.getErrorMessage())) self.findHash_done(HashObject(), req, url, orig_resp, d)
def _ebRender(self, failure): self._err(failure) if isinstance(failure.value, Fault): return failure.value return Fault(self.FAILURE, "An unhandled exception occurred: %s" % failure.getErrorMessage())
def _fail(failure): print "Discovery result:", failure.getErrorMessage() d.errback(failure)
def error(self, failure, op=""): clientLog.error('Error in %s: %s' % (op, str(failure.getErrorMessage()))) if reactor.running: reactor.stop()