Runs the given callback with exception handling.

        If the callback is a coroutine, returns its Future. On error, aborts the
        websocket connection and returns None.
434909
def _run_callback(
        self, callback: Callable, *args: Any, **kwargs: Any
    ) -> "Optional[Future[Any]]":
        
        try:
            result = callback(*args, **kwargs)
        except Exception:
            self.handler.log_exception(*sys.exc_info())
            self._abort()
            return None
        else:
            if result is not None:
                result = gen.convert_yielded(result)
                assert self.stream is not None
                self.stream.io_loop.add_future(result, lambda f: f.result())
            return result
133298
def _function_handler(function, args, kwargs, future):
    """"""
    future.set_running_or_notify_cancel()

    try:
        result = function(*args, **kwargs)
    except BaseException as error:
        error.traceback = format_exc()
        future.set_exception(error)
    else:
        future.set_result(result)
587120
def _on_error(self, websock, e):
        '''
        
        '''
        if isinstance(e, (
            websocket.WebSocketConnectionClosedException,
            ConnectionResetError)):
            self.logger.error('websocket closed, did chrome die?')
        else:
            self.logger.error(
                    'exception from websocket receiver thread',
                    exc_info=1)
        brozzler.thread_raise(self.calling_thread, BrowsingException)
480592
def run(self):
        
        while not self._request_shutdown:

            # Find out if we have any data pending from the
            # server
            try:

                # If we've been asked to stop running the
                # request loop. We'll just sit and wait
                # till we get asked to run again
                if self._state not in [STATE_AUTHENTICATING,STATE_WEBSOCKET_CONNECTED,STATE_CONNECTED]:
                    self._request_loop_notify_restart.acquire()
                    self._request_loop_notify_restart.wait(self._loop_timeout)
                    self._request_loop_notify_restart.release()
                    continue

                # If we don't have a websocket defined.
                # we don't go further either
                elif not self.ws:
                    logger.debug("No longer have a websocket. Marking disconnected")
                    self._state = STATE_DISCONNECTED
                    continue

                # Okay, we think we're okay so let's try and read some data
                data = self.ws.recv()
            except io.BlockingIOError:
                continue
            except websocket.WebSocketTimeoutException:
                continue
            except websocket.WebSocketConnectionClosedException as ex:
                logger.debug("WebSocketConnectionClosedException: Requesting disconnect:".format(ex))
                self.disconnect()

                # If the server disconnected, let's try and reconnect
                # back to the service after a random few seconds
                if self.auto_reconnect:
                    # As doing a reconnect would block and would then
                    # prevent us from ticking the websoocket, we'll
                    # go into a subthread to deal with the reconnection
                    def reconnect():
                        self.reconnect()
                    t = threading.Thread(target=reconnect)
                    t.start()

                    # FIXME: need to randomly wait
                    time.sleep(1)
                    if not data: continue
            except Exception as ex:
                logger.error("ERROR in main loop: {}".format(ex))
                continue

            try:
                logger.debug("<RCV: {}".format(data))
                message = WampMessage.loads(data)
                logger.debug("<RCV: {}".format(message.dump()))
                try:
                    code_name = message.code_name.lower()
                    handler_name = "handle_"+code_name
                    handler_function = getattr(self,handler_name)
                    handler_function(message)
                except AttributeError as ex:
                    self.handle_unknown(message)
            except Exception as ex:
                logger.error("ERROR in main loop: {}".format(ex))
572960
def main():
    """"""
    # Helper method so that the coroutine exits cleanly if an exception
    # happens (which would leave resources dangling)
    async def _run_application(loop):
        try:
            return await cli_handler(loop)

        except KeyboardInterrupt:
            pass  # User pressed Ctrl+C, just ignore it

        except SystemExit:
            pass  # sys.exit() was used - do nothing

        except:  # pylint: disable=bare-except  # noqa
            import traceback

            traceback.print_exc(file=sys.stderr)
            sys.stderr.writelines(
                '\n>>> An error occurred, full stack trace above\n')

        return 1

    try:
        loop = asyncio.get_event_loop()
        return loop.run_until_complete(_run_application(loop))
    except KeyboardInterrupt:
        pass

    return 1
1168910
public void callback(final Callback callback)
    {
        Runnable runnable = new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    callback.result(queryId, awaitResult());
                }
                catch (Exception e)
                {
                    callback.error(queryId, e);
                }
            }
        };
        EXECUTOR_SERVICE.submit(runnable);
    }
243432
def __handler(self, connection, event):
        
        try:
            # Find local handler
            method = getattr(self, "on_{0}".format(event.type))
        except AttributeError:
            pass
        else:
            try:
                # Call it
                return method(connection, event)
            except Exception as ex:
                logging.exception("Error calling handler: %s", ex)
972481
def _worker_handler(future, worker, pipe, timeout):
    
    result = _get_result(future, pipe, timeout)

    if isinstance(result, BaseException):
        if isinstance(result, ProcessExpired):
            result.exitcode = worker.exitcode

        future.set_exception(result)
    else:
        future.set_result(result)

    if worker.is_alive():
        stop_process(worker)
717989
def _execute(self, handler, *args, **kwargs):
        
        # difference to Axel Events: we don't use a timeout and execute all handlers in same thread
        # FIXME: =>possible problem:
        #                       blocking of event firing when user gives a long- or infinitly-running callback function
        # (in Python it doesn't seem possible to forcefully kill a thread with clean ressource releasing,
        #  a thread has to cooperate und behave nice...
        #  execution and killing a process would be possible, but has data corruption problems with queues
        #  and possible interprocess communication problems with given handler/callback function)

        result = None
        exc_info = None

        try:
            result = handler(*args, **kwargs)
        except Exception:
            exc_info = sys.exc_info()
        if exc_info:
            return exc_info
        return result
474437
async def handle_websocket_exception(self, error: Exception) -> Optional[Response]:
        
        await got_websocket_exception.send(self, exception=error)

        self.log_exception(sys.exc_info())

        internal_server_error = all_http_exceptions[500]()
        handler = self._find_exception_handler(internal_server_error)

        if handler is None:
            return internal_server_error.get_response()
        else:
            return await self.finalize_websocket(await handler(error), from_error_handler=True)
361146
def run(self, limit=None, timeout=None):
        
        counter = 0
        self.stream = sseclient.SSEClient(self.endpoint)
        while True:
            with utils.Timeout(timeout):
                try:
                    event = next(self.stream)
                except StopIteration:
                    continue
                else:
                    if not event.data:
                        continue
                    self.main_callback(event.data)
                    counter += 1
                    if limit and counter >= limit:
                        return
498964
def run(self):
        ''''''
        while not self.wait(self.delay()):
            try:
                logger.info('Invoking callback %s', self.callback)
                self.callback()
            except StandardError:
                logger.exception('Callback failed')
242077
@FFDCIgnore(Throwable.class)
    void run() {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        if (!state.setRunning()) {
            if (trace && tc.isDebugEnabled())
                Tr.debug(this, tc, "unable to run", state.get());
            nsRunEnd = System.nanoTime();
            if (callback != null)
                callback.onEnd(task, this, null, true, 0, null); // aborted, queued task will never run
            return;
        }

        boolean aborted = true;
        Object callbackContext = null;
        thread = Thread.currentThread();
        try {
            if (callback == null)
                aborted = false;
            else {
                callbackContext = callback.onStart(task, this);
                aborted = state.get() == CANCELED;
            }

            if (aborted)
                nsRunEnd = System.nanoTime();
            else {
                T t;
                if (callable == null) {
                    runnable.run();
                    t = predefinedResult;
                } else {
                    t = callable.call();
                }

                nsRunEnd = System.nanoTime();

                if (result.compareAndSet(state, t)) {
                    state.releaseShared(SUCCESSFUL);
                    if (latch != null)
                        latch.countDown(t);
                } else if (Integer.valueOf(CANCELED).equals(result.get())) {
                    if (trace && tc.isDebugEnabled())
                        Tr.debug(this, tc, "canceled during/after run");
                    // Prevent dirty read of state during onEnd before the canceling thread transitions the state to CANCELING/CANCELED
                    while (state.get() == RUNNING)
                        Thread.yield();
                }

                if (trace && tc.isDebugEnabled())
                    Tr.debug(this, tc, "run", t);
            }

            if (callback != null)
                try {
                    callback.onEnd(task, this, callbackContext, aborted, 0, null);
                } catch (Throwable x) {
                }
        } catch (Throwable x) {
            if (trace && tc.isDebugEnabled())
                Tr.debug(this, tc, "run", x);

            nsRunEnd = System.nanoTime();

            if (result.compareAndSet(state, x)) {
                state.releaseShared(aborted ? ABORTED : FAILED);
                if (latch != null)
                    latch.countDown();
            }

            if (callback != null)
                callback.onEnd(task, this, callbackContext, aborted, 0, x);
        } finally {
            thread = null;
            // Prevent accidental interrupt of subsequent operations by awaiting the transition from CANCELING to CANCELED
            while (state.get() == CANCELING)
                Thread.yield();
        }
    }
1113209
protected Future<?> callOnError(final Exception exc) throws IllegalStateException {
		if(isClosed()) throw new IllegalStateException("Socket is closed");
		return listenerManager.enqueueEvent(
			new ConcurrentListenerManager.Event<SocketContextListener>() {
				@Override
				public Runnable createCall(final SocketContextListener listener) {
					return new Runnable() {
						@Override
						public void run() {
							listener.onError(
								AbstractSocketContext.this,
								exc
							);
						}
					};
				}
			}
		);
	}
992282
def _handle_client_exception():
    
    try:
        yield

    except _ClientException as exception:
        if exception.http_status in _ERROR_CODES:
            raise _ERROR_CODES[exception.http_status](
                exception.http_reason)
        raise
1276788
def run(self) -> None:
        
        if self.running or self.finished:
            return
        try:
            self.running = True
            while True:
                future = self.future
                if future is None:
                    raise Exception("No pending future")
                if not future.done():
                    return
                self.future = None
                try:
                    exc_info = None

                    try:
                        value = future.result()
                    except Exception:
                        exc_info = sys.exc_info()
                    future = None

                    if exc_info is not None:
                        try:
                            yielded = self.gen.throw(*exc_info)  # type: ignore
                        finally:
                            # Break up a reference to itself
                            # for faster GC on CPython.
                            exc_info = None
                    else:
                        yielded = self.gen.send(value)

                except (StopIteration, Return) as e:
                    self.finished = True
                    self.future = _null_future
                    future_set_result_unless_cancelled(
                        self.result_future, _value_from_stopiteration(e)
                    )
                    self.result_future = None  # type: ignore
                    return
                except Exception:
                    self.finished = True
                    self.future = _null_future
                    future_set_exc_info(self.result_future, sys.exc_info())
                    self.result_future = None  # type: ignore
                    return
                if not self.handle_yield(yielded):
                    return
                yielded = None
        finally:
            self.running = False
1020271
async def run_async(self, endpoint: str):
        
        self._connect(endpoint)

        # spawn an initial listen task
        listen_task = asyncio.ensure_future(self._socket.recv_multipart())
        task_list = [listen_task]

        while True:
            dones, pendings = await asyncio.wait(task_list, return_when=asyncio.FIRST_COMPLETED)

            # grab one "done" task to handle
            task_list, done_list = list(pendings), list(dones)
            done = done_list.pop()
            task_list += done_list

            if done == listen_task:
                try:
                    # empty_frame may either be:
                    # 1. a single null frame if the client is a REQ socket
                    # 2. an empty list (ie. no frames) if the client is a DEALER socket
                    identity, *empty_frame, msg = done.result()
                    request = from_msgpack(msg)

                    # spawn a processing task
                    task_list.append(asyncio.ensure_future(
                        self._process_request(identity, empty_frame, request)))
                except Exception as e:
                    if self.serialize_exceptions:
                        _log.exception('Exception thrown in Server run loop during request '
                                       'reception: {}'.format(str(e)))
                    else:
                        raise e
                finally:
                    # spawn a new listen task
                    listen_task = asyncio.ensure_future(self._socket.recv_multipart())
                    task_list.append(listen_task)
            else:
                # if there's been an exception during processing, consider reraising it
                try:
                    done.result()
                except Exception as e:
                    if self.serialize_exceptions:
                        _log.exception('Exception thrown in Server run loop during request '
                                       'dispatch: {}'.format(str(e)))
                    else:
                        raise e