this is called by web socket thread not Chorus interpreter so log don't throw ChorusException, log errors instead
5961
public void stepSucceeded(StepSucceededMessage stepSuccessMessage) {
        ExecutingStep s = executingStep.get();
        if ( ! s.getExecutionUUID().equals(stepSuccessMessage.getExecutionId())) {
            //This could happen if chorus interpreter timed out the previous step while waiting for the reply
            //Hence log to debug rather than error
            log.debug("Received a StepSucceededMessage for a step execution id " + stepSuccessMessage.getExecutionId() + " which did not match the currently executing step " + s.getExecutionUUID());
        } else {
            s.getCompletableFuture().complete(stepSuccessMessage);
        }
    }
151791
public static Thread pipeAsynchronously(final InputStream is, final ErrorHandler errorHandler, final boolean closeResources, final OutputStream... os) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    pipeSynchronously(is, closeResources, os);
                } catch (Throwable th) {
                    if (errorHandler != null) {
                        errorHandler.onThrowable(th);
                    }
                }
            }
        };
        t.setDaemon(true);
        t.start();
        return t;
    }
664054
def _recv_thread(self):
        
        for msg, metadata in self._source:
            if msg.msg_type:
                self._call(msg, **metadata)
        # Break any upstream iterators
        for sink in self._sinks:
            i = sink()
            if i is not None:
                i.breakiter()
        self._dead = True
891194
private static void logException(String tag, Throwable t) {
        Log.e(tag, "%s in thread %d", t, threadId());
        t.printStackTrace();
    }
1233202
def try_catch(func, *args, **kwargs):
    '''
    
    '''
    try:
        return log_debug(func, *args, **kwargs)
    except Exception as exc:
        logging.debug('Error in "%s" in thread %s: %s', func.__name__, current_thread(), exc)
        return exc
127014
@Override
    public void onRPCError(int handle, int code, String text) {
        if (handle == asyncHandle) {
            asyncHandle = 0;
            ZKUtil.fireEvent(new AsyncRPCErrorEvent(rpcName, target, code, text, handle));
            rpcName = null;
        }
    }
581651
@SuppressWarnings("InfiniteLoopStatement")
	public static void main(String[] args) throws Exception {
		LoggingCallback loggingCallback = new LoggingCallback();
		loggingCallback.setLevel(Level.INFO);
		SimonManager.callback().addCallback(loggingCallback);
		Random random = new Random();

		register();
		try {
			while (true) {
				final int task = random.nextInt(TASK_SPREAD) + TASK_MIN;
				new Thread() {
					public void run() {
						try (Split split = SimonManager.getStopwatch(TASK_STOPWATCH).start()) {
							Thread.sleep(task);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}.start();
				int sleep = random.nextInt(NEW_TASK_SPREAD) + NEW_TASK_MIN;
				Thread.sleep(sleep);
			}
		} finally {
			unregister();
		}
	}
1206025
public void onReadFailure(Throwable t) {
        ConnectionState event = null;
        synchronized (this) {
            if (this.state == ConnectionState.CLOSED) {
                // already closed
                return;
            }

            // Build out Close Reason
            String reason = "WebSocket Read Failure";
            if (t instanceof EOFException) {
                reason = "WebSocket Read EOF";
                Throwable cause = t.getCause();
                if ((cause != null) && (StringUtils.hasText(cause.getMessage()))) {
                    reason = "EOF: " + cause.getMessage();
                }
            } else {
                if (StringUtils.hasText(t.getMessage())) {
                    reason = t.getMessage();
                }
            }

            CloseInfo close = new CloseInfo(StatusCode.ABNORMAL, reason);

            finalClose.compareAndSet(null, close);

            this.cleanClose = false;
            this.state = ConnectionState.CLOSED;
            this.closeInfo = close;
            this.inputAvailable = false;
            this.outputAvailable = false;
            this.closeHandshakeSource = CloseHandshakeSource.ABNORMAL;
            event = this.state;
        }
        notifyStateListeners(event);
    }
921778
@Override
  public synchronized void onNext(final RuntimeStart runtimeStart) {
    LOG.log(Level.FINEST, "HttpRuntimeStartHandler: {0}", runtimeStart);
    try {
      httpServer.start();
      LOG.log(Level.FINEST, "HttpRuntimeStartHandler complete.");
    } catch (final Exception e) {
      LOG.log(Level.SEVERE, "HttpRuntimeStartHandler cannot start the Server. {0}", e);
      throw new RuntimeException("HttpRuntimeStartHandler cannot start the Server.", e);
    }
  }
194251
private static String fork(String sjavac, String portfile, String logfile, int poolsize, int keepalive,
            final PrintStream err, String stdouterrfile, String background)
            throws IOException, ProblemException {
        if (stdouterrfile != null && stdouterrfile.trim().equals("")) {
            stdouterrfile = null;
        }
        final String startserver = "--startserver:portfile=" + portfile + ",logfile=" + logfile + ",stdouterrfile=" + stdouterrfile + ",poolsize=" + poolsize + ",keepalive="+ keepalive;

        if (background.equals("true")) {
            sjavac += "%20" + startserver;
            sjavac = sjavac.replaceAll("%20", " ");
            sjavac = sjavac.replaceAll("%2C", ",");
            // If the java/sh/cmd launcher fails the failure will be captured by stdouterr because of the redirection here.
            String[] cmd = {"/bin/sh", "-c", sjavac + " >> " + stdouterrfile + " 2>&1"};
            if (!(new File("/bin/sh")).canExecute()) {
                ArrayList<String> wincmd = new ArrayList<String>();
                wincmd.add("cmd");
                wincmd.add("/c");
                wincmd.add("start");
                wincmd.add("cmd");
                wincmd.add("/c");
                wincmd.add(sjavac + " >> " + stdouterrfile + " 2>&1");
                cmd = wincmd.toArray(new String[wincmd.size()]);
            }
            Process pp = null;
            try {
                pp = Runtime.getRuntime().exec(cmd);
            } catch (Exception e) {
                e.printStackTrace(err);
                e.printStackTrace(new PrintWriter(stdouterrfile));
            }
            StringBuilder rs = new StringBuilder();
            for (String s : cmd) {
                rs.append(s + " ");
            }
            return rs.toString();
        }

        // Do not spawn a background server, instead run it within the same JVM.
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    JavacServer.startServer(startserver, err);
                } catch (Throwable t) {
                    t.printStackTrace(err);
                }
            }
        };
        t.start();
        return "";
    }
936829
protected void onRPCError(int asyncHandle, int asyncError, String text) {
        IAsyncRPCEvent callback = getCallback(asyncHandle);
        
        if (callback != null) {
            callback.onRPCError(asyncHandle, asyncError, text);
        }
    }
1232781
def atlas_log_socket_error( method_invocation, peer_hostport, se ):
    
    if isinstance( se, socket.timeout ):
        log.debug("%s %s: timed out (socket.timeout)" % (method_invocation, peer_hostport))

    elif isinstance( se, socket.gaierror ):
        log.debug("%s %s: failed to query address or info (socket.gaierror)" % (method_invocation, peer_hostport ))

    elif isinstance( se, socket.herror ):
        log.debug("%s %s: failed to query host info (socket.herror)" % (method_invocation, peer_hostport ))

    elif isinstance( se, socket.error ):
        if se.errno == errno.ECONNREFUSED:
            log.debug("%s %s: is unreachable (socket.error ECONNREFUSED)" % (method_invocation, peer_hostport))
        elif se.errno == errno.ETIMEDOUT:
            log.debug("%s %s: timed out (socket.error ETIMEDOUT)" % (method_invocation, peer_hostport))
        else:
            log.debug("%s %s: socket error" % (method_invocation, peer_hostport))
            log.exception(se)

    else:
        log.debug("%s %s: general exception" % (method_invocation, peer_hostport))
        log.exception(se)
472641
static void pingNode(final Node node, final HttpServerExchange exchange, final PingCallback callback) {
        if (node == null) {
            callback.failed();
            return;
        }

        final int timeout = node.getNodeConfig().getPing();
        exchange.dispatch(exchange.isInIoThread() ? SameThreadExecutor.INSTANCE : exchange.getIoThread(), new Runnable() {
            @Override
            public void run() {
                node.getConnectionPool().connect(null, exchange, new ProxyCallback<ProxyConnection>() {
                    @Override
                    public void completed(final HttpServerExchange exchange, ProxyConnection result) {
                        final RequestExchangeListener exchangeListener = new RequestExchangeListener(callback, NodeHealthChecker.NO_CHECK, false);
                        exchange.dispatch(SameThreadExecutor.INSTANCE, new ConnectionPoolPingTask(result, exchangeListener, node.getNodeConfig().getConnectionURI()));
                        // Schedule timeout task
                        scheduleCancelTask(exchange.getIoThread(), exchangeListener, timeout, TimeUnit.SECONDS);
                    }

                    @Override
                    public void failed(HttpServerExchange exchange) {
                        callback.failed();
                    }

                    @Override
                    public void queuedRequestFailed(HttpServerExchange exchange) {
                        callback.failed();
                    }

                    @Override
                    public void couldNotResolveBackend(HttpServerExchange exchange) {
                        callback.failed();
                    }

                }, timeout, TimeUnit.SECONDS, false);
            }
        });
    }
897452
@Override
	public void invoke(IN value) throws Exception {
		byte[] msg = schema.serialize(value);

		try {
			outputStream.write(msg);
			if (autoFlush) {
				outputStream.flush();
			}
		}
		catch (IOException e) {
			// if no re-tries are enable, fail immediately
			if (maxNumRetries == 0) {
				throw new IOException("Failed to send message '" + value + "' to socket server at "
						+ hostName + ":" + port + ". Connection re-tries are not enabled.", e);
			}

			LOG.error("Failed to send message '" + value + "' to socket server at " + hostName + ":" + port +
					". Trying to reconnect..." , e);

			// do the retries in locked scope, to guard against concurrent close() calls
			// note that the first re-try comes immediately, without a wait!

			synchronized (lock) {
				IOException lastException = null;
				retries = 0;

				while (isRunning && (maxNumRetries < 0 || retries < maxNumRetries)) {

					// first, clean up the old resources
					try {
						if (outputStream != null) {
							outputStream.close();
						}
					}
					catch (IOException ee) {
						LOG.error("Could not close output stream from failed write attempt", ee);
					}
					try {
						if (client != null) {
							client.close();
						}
					}
					catch (IOException ee) {
						LOG.error("Could not close socket from failed write attempt", ee);
					}

					// try again
					retries++;

					try {
						// initialize a new connection
						createConnection();

						// re-try the write
						outputStream.write(msg);

						// success!
						return;
					}
					catch (IOException ee) {
						lastException = ee;
						LOG.error("Re-connect to socket server and send message failed. Retry time(s): " + retries, ee);
					}

					// wait before re-attempting to connect
					lock.wait(CONNECTION_RETRY_DELAY);
				}

				// throw an exception if the task is still running, otherwise simply leave the method
				if (isRunning) {
					throw new IOException("Failed to send message '" + value + "' to socket server at "
							+ hostName + ":" + port + ". Failed after " + retries + " retries.", lastException);
				}
			}
		}
	}
1237090
function proxyError (err) {
    reverseProxy.destroy();

    process.nextTick(function () {
      //
      // Destroy the incoming socket in the next tick, in case the error handler
      // wants to write to it.
      //
      socket.destroy();
    });

    self.emit('webSocketProxyError', req, socket, head);
  }
1355400
private void log(@NonNull Logger log, @NonNull Throwable t, String msg) {
        log.f(msg + ". Error calling services. " + t.getLocalizedMessage(), t);
    }
1272783
@Override
	public void processMessage(final WebSocketMessage webSocketData) {

		setDoTransactionNotifications(true);

		final SecurityContext securityContext = getWebSocket().getSecurityContext();

		try {

			final String uuid  = webSocketData.getId();
			int sequenceNumber = webSocketData.getNodeDataIntegerValue("chunkId");
			int chunkSize      = webSocketData.getNodeDataIntegerValue("chunkSize");
			int chunks         = webSocketData.getNodeDataIntegerValue("chunks");
			Object rawData     = webSocketData.getNodeData().get("chunk");

			byte[] data        = new byte[0];

			if (rawData != null) {

				if (rawData instanceof String) {

					logger.debug("Raw data: {}", rawData);

//                                        data = Base64.decodeBase64(((String)rawData).getBytes("UTF-8"));
					data = Base64.decode(((String) rawData));

					logger.debug("Decoded data: {}", data);

				}

			}

			final File file = (File) getNode(uuid);
			if (file.isTemplate()) {

				logger.warn("No write permission, file is in template mode: {}", new Object[] {file.toString()});
				getWebSocket().send(MessageBuilder.status().message("No write permission, file is in template mode").code(400).build(), true);
				return;

			}

			if (!file.isGranted(Permission.write, securityContext)) {

				logger.warn("No write permission for {} on {}", new Object[] {getWebSocket().getCurrentUser().toString(), file.toString()});
				getWebSocket().send(MessageBuilder.status().message("No write permission").code(400).build(), true);
				return;

			}

			getWebSocket().handleFileChunk(uuid, sequenceNumber, chunkSize, data, chunks);

			if (sequenceNumber+1 == chunks) {

				FileHelper.updateMetadata(file);

				file.increaseVersion();

				getWebSocket().removeFileUploadHandler(uuid);

				logger.debug("File upload finished. Checksum: {}, size: {}", new Object[]{ file.getChecksum(), file.getSize() });

			}

			final long currentSize = (long)(sequenceNumber * chunkSize) + data.length;

			// This should trigger setting of lastModifiedDate in any case
			getWebSocket().send(MessageBuilder.status().code(200).message("{\"id\":\"" + file.getUuid() + "\", \"name\":\"" + file.getName() + "\",\"size\":" + currentSize + "}").build(), true);

		} catch (IOException | FrameworkException ex) {

			String msg = ex.toString();

			// return error message
			getWebSocket().send(MessageBuilder.status().code(400).message("Could not process chunk data: ".concat((msg != null)
				? msg
				: "")).build(), true);
		}
	}