Perform the callback chain going back and forth between the callback
        and errback as needed.

        If an exception is raised and the entire chain is gone through without a valid
        errback then its simply logged.
768099
def _start_callbacks(self, result, exception):
        
        if self._cancelled:
            raise CancelledError()
        if self.called:
            raise AlreadyCalledError()

        self._result = result
        self._exception = exception
        if self._exception:
            self._tb_info = ''.join(traceback.format_tb(sys.exc_info()[2])) 
        self.called = True
        self._do_callbacks()
328018
def _run_callback(self, callback):
        
        try:
            ret = callback()
            if ret is not None:
                from . import gen
                # Functions that return Futures typically swallow all
                # exceptions and store them in the Future.  If a Future
                # makes it out to the IOLoop, ensure its exception (if any)
                # gets logged too.
                try:
                    ret = gen.convert_yielded(ret)
                except gen.BadYieldError:
                    # It's not unusual for add_callback to be used with
                    # methods returning a non-None and non-yieldable
                    # result, which should just be ignored.
                    pass
                else:
                    self.add_future(ret, self._discard_future_result)
        except Exception:
            self.handle_callback_exception(callback)
90253
def _exception_free_callback(self, callback, *args, **kwargs):
        
        try:
            return callback(*args, **kwargs)
        except Exception:
            self._logger.exception("An exception occurred while calling a hook! ",exc_info=True)
            return None
292418
public void handleInit(ChaincodeMessage message) throws InvalidTransactionException  {
		Runnable task = () -> {
			ChaincodeMessage nextStatemessage = null;
			boolean send = true;
			try {
				// Get the function and args from Payload
				ChaincodeInput input;
				try {
					input = ChaincodeInput.parseFrom(message.getPayload());
				} catch (InvalidProtocolBufferException e) {
                    nextStatemessage = ChaincodeMessage.newBuilder()
                            .setType(ERROR)
                            .setPayload(ByteString.copyFromUtf8("Unmarshall error -"
                                    + e.getMessage()))
                            .setTxid(message.getTxid())
                            .build();
                    return;
				}

				//			// Mark as a transaction (allow put/del state)
				markIsTransaction(message.getTxid(), true);

				// Create the ChaincodeStub which the chaincode can use to callback
				ChaincodeStub stub = new ChaincodeStub(message.getTxid(), this, message.getSecurityContext());
				// Call chaincode's Run
				ByteString result;
				try {
					result = chaincode.runHelper(stub, getFunction(input.getArgsList()), getParameters(input.getArgsList()));
				} catch (Exception e) {
					// Send ERROR message to chaincode support and change state
					logger.debug(String.format("[%s]Init failed. Sending %s", shortID(message), ERROR));
					nextStatemessage = ChaincodeMessage.newBuilder()
							.setType(ERROR)
							.setPayload(ByteString.copyFromUtf8(e.getMessage()))
							.setTxid(message.getTxid())
							.build();
					return;
				} finally {
					// delete isTransaction entry
					deleteIsTransaction(message.getTxid());
				}

				// Send COMPLETED message to chaincode support and change state
				nextStatemessage = ChaincodeMessage.newBuilder()
						.setType(COMPLETED)
						.setPayload(result)
						.setTxid(message.getTxid())
						.build();

				logger.debug(String.format(String.format("[%s]Init succeeded. Sending %s",
						shortID(message), COMPLETED)));

				//TODO put in all exception states
			}
		 finally {
				triggerNextState(nextStatemessage, send);
			}
		};

		//Run above task
		new Thread(task).start();
	}
705740
function(err) {
		/**
		 * If err is an Error object, break the chain and call catch
		 */
		if (err && (err.constructor.name === "Error" || err.constructor.name === "TypeError") && this.onCatch) {
			this.onCatch(err);
			return;
		}

		var nextFn = this.fnStack.shift();
		if (nextFn) {
			/**
			 * Ensure arguments are passed as an Array
			 */
			var args = Array.prototype.slice.call(arguments);
			return this.execute(nextFn.fn, args);
		}
	}
125098
def add_callbacks(self, future, callback, errback):
        
        assert future is not None
        if callback is None:
            assert errback is not None
            future.addErrback(errback)
        else:
            # Twisted allows errback to be None here
            future.addCallbacks(callback, errback)
        return future
1054944
public final T makeCall() throws IOException {
    while (true) {
      try {
        return call();
      } catch (ConnectException e) {
        // We fall back only after ConnectException
        try {
          // Fall back to secondary tracker and reconnect to new JT
          reconnectToNewJobTracker(0);
        } catch (IOException f) {
          LOG.error("Fallback process failed with ", f);
          // Re-throw original exception
          throw e;
        }
      } catch (IOException e) {
        // the subclass of fallback caller should provide
        // logic here. We will retry in most cases
        handleIOException(e);
      }
    }
  }
532912
function (err, params) {
                if (!err) {
                  callback && callback(null, params);
                }
                else {
                  callback && callback(err.message || err);
                }
              }
221586
def _do_cb(self, cb, error_cb, *args, **kw):
        
        try:
            res = self.work(*args, **kw)
        except Exception as e:
            if error_cb is None:
                show_err()
            elif error_cb:
                error_cb(e)
        else:
            # Success, let's call away!
            cb(res)
1151833
function handleCallback(err, url, callback) {
	if (callback.__called) {
		return;
	}
	callback.__called = true;
	callback(err, {
		url: url,
		title: callback.__title,
		count: callback.__redirectCounter,
		tracks: callback.__tracks
	});
}
1120374
function attemptCallback(filePath, callback, attempts) {

	try {

		callback();
		return;

	} catch (error) {

		if (attempts === 0) {
			console.error('takeown: callback failed - exceeded attempts');
			throw error;
		}

		switch (error.code) {

			case 'EPERM':
			case 'EACCES':
			case 'EBUSY':
			case 'ENOTEMPTY':
				return attemptCallback(filePath, callback, --attempts);

			default:
				throw error;
		}
	}
}
1209478
function execCallback(err, stream) {
    if (err) throw err;
    stream
        .on('close', function (code, signal) { console.log('Stream closed with code ' + code + ' and signal ' + signal); conn.end() })
        .on('data', function (data) { console.log(data); })
        .stderr.on('data', function (err) { console.log('!!!!!!!!!!!!!! Error: ' + err); });
}
416178
function errorToExceptionCallback(cb) {
    var browser = this;

    return function errorWrapped(err) {
        if (err) throw err;
        if (cb) {
            cb.apply(browser, _.tail(arguments));
        }
    };
}
1056547
def safe_invoke_callback(callback, *args, **kwargs):
    """"""
    # pylint: disable=bare-except
    # We intentionally want to swallow all exceptions.
    try:
        return callback(*args, **kwargs)
    except Exception:
        _LOGGER.exception("Error while executing Future callback.")
951010
private void processCallback(final Callback callback) {
        try {
            JsonNode result = handleCallback(callback);
            this.getClient().completeCallback(callback, null, result);
        } catch (JsiiException e) {
            this.getClient().completeCallback(callback, e.getMessage(), null);
        }
    }
1362964
def _do_callbacks(self):
        """"""
        self._done = False

        while self._callbacks and not self._cancelled:
            cb, eb, cb_args, cb_kwargs, eb_args, eb_kwargs = self._callbacks.pop()
            if cb and not self._exception:
                try:
                    self._result = cb(self._result, *cb_args, **cb_kwargs)
                    self._exception = False
                except Exception as e:
                    #logger.exception('deferred got exception while doing callback')
                    self._exception = True
                    self._result = e
                    self._tb_info = ''.join(traceback.format_tb(sys.exc_info()[2]))
            elif eb and self._exception:
                try:
                    self._result = eb(self._result, *eb_args, **eb_kwargs)
                    self._exception = False
                except Exception as e:
                    #logger.exception('deferred got exception while doing callback')
                    self._exception = True
                    self._result = e
                    self._tb_info = ''.join(traceback.format_tb(sys.exc_info()[2]))


        if self._exception:
            if Deferred.warnings:
                logger.warn('Unhandled Exception: ' + str(self._result))
            self._last_exception.exception = self._result
            self._last_exception.tb_info = self._tb_info
        else:
            self._last_exception.exception = None
            self._last_exception.tb_info = None

        self._done = True
1060766
def loop_handle_server_calls
      fail 'not started' if running_state == :not_started
      while running_state == :running
        begin
          an_rpc = @server.request_call
          break if (!an_rpc.nil?) && an_rpc.call.nil?
          active_call = new_active_server_call(an_rpc)
          unless active_call.nil?
            @pool.schedule(active_call) do |ac|
              c, mth = ac
              begin
                rpc_descs[mth].run_server_method(
                  c,
                  rpc_handlers[mth],
                  @interceptors.build_context
                )
              rescue StandardError
                c.send_status(GRPC::Core::StatusCodes::INTERNAL,
                              'Server handler failed')
              end
            end
          end
        rescue Core::CallError, RuntimeError => e
          # these might happen for various reasons.  The correct behavior of
          # the server is to log them and continue, if it's not shutting down.
          if running_state == :running
            GRPC.logger.warn("server call failed: #{e}")
          end
          next
        end
      end
      # @running_state should be :stopping here
      @run_mutex.synchronize do
        transition_running_state(:stopped)
        GRPC.logger.info("stopped: #{self}")
        @server.close
      end
    end