com.google.common.base.Throwables#getStackTraceAsString ( )源码实例Demo

下面列出了com.google.common.base.Throwables#getStackTraceAsString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: xtext-eclipse   文件: XtextBuildConsole.java
@Override
public void log(Object obj) {
	if (delegate != null) {
		delegate.log(obj);
	}

	IConsoleManager consoleManager = ConsolePlugin.getDefault().getConsoleManager();
	XtextBuildConsole console = null;
	for (IConsole c : consoleManager.getConsoles()) {
		if (c instanceof XtextBuildConsole) {
			console = (XtextBuildConsole) c;
			break;
		}
	}
	if (console != null) {
		String str = null;
		if (obj instanceof Throwable) {
			str = Throwables.getStackTraceAsString((Throwable) obj);
		} else {
			str = obj.toString();
		}
		console.println("[" + Thread.currentThread().getName() + "] " + str);
		consoleManager.showConsoleView(console);
	}
}
 
源代码2 项目: n4js   文件: N4JSGlobalScopeProvider.java
@Override
protected IScope getScope(IScope parent, Resource context, boolean ignoreCase, EClass type,
		Predicate<IEObjectDescription> filter) {

	IScope result = null;
	try {
		result = super.getScope(parent, context, ignoreCase, type, filter);
	} catch (IllegalStateException ise) {
		String msg = "ERROR for " + context.getURI() + " ::\n" + Throwables.getStackTraceAsString(ise);
		System.err.println(msg);
		return IScope.NULLSCOPE;
	}
	if (isSubtypeOfType(type)) {
		result = new VisibilityAwareTypeScope(result, typeVisibilityChecker, context);
		return result;
	}
	if (isSubtypeOfIdentifiable(type)) {
		result = new VisibilityAwareIdentifiableScope(result, varVisibilityChecker, typeVisibilityChecker, context);
		return result;
	}
	return result;
}
 
源代码3 项目: incubator-gobblin   文件: SingleHelixTask.java
@Override
public TaskResult run() {
  try {
    logger.info(String
        .format("Waiting for a single task process to finish. job name: %s. job id: %s",
            this.jobName, this.jobId));
    int exitCode = this.taskProcess.waitFor();
    if (exitCode == 0) {
      logger.info("Task process finished. job name: {}. job id: {}", this.jobName, this.jobId);
      return new TaskResult(TaskResult.Status.COMPLETED, "");
    } else {
      logger.warn("Task process failed with exitcode ({}). job name: {}. job id: {}", exitCode,
          this.jobName, this.jobId);
      return new TaskResult(TaskResult.Status.FATAL_FAILED, "Exit code: " + exitCode);
    }
  } catch (final Throwable t) {
    logger.error("SingleHelixTask failed due to " + t.getMessage(), t);
    return new TaskResult(TaskResult.Status.FAILED, Throwables.getStackTraceAsString(t));
  }
}
 
源代码4 项目: science-journal   文件: TrackerConstants.java
public static String createLabelFromStackTrace(Throwable t) {
  String s = Throwables.getStackTraceAsString(t);
  s = s.replace("\n\t", " ");
  if (s.length() > MAX_LABEL_LENGTH) {
    s = s.substring(0, MAX_LABEL_LENGTH);
  }
  return s;
}
 
源代码5 项目: beihu-boot   文件: ServiceExceptionHandler.java
@ExceptionHandler(Exception.class)
public JsonResponse handleException(Exception e){
	String stackTraceAsString = Throwables.getStackTraceAsString(e);
	LOGGER.error("【ServiceExceptionHandler - Exception】\r\n [{}]", stackTraceAsString);
	defaultMailSender.warn("【系统异常】", stackTraceAsString);
	return BasicResponse.error(new ServiceException(BasicServiceCode.FAILED));
}
 
@Override
public String toString() {
	try {
		StringBasedTextRegionAccessDiff regions = create();
		return new TextRegionAccessToString().withRegionAccess(regions).toString();
	} catch (Throwable t) {
		return t.getMessage() + "\n" + Throwables.getStackTraceAsString(t);
	}
}
 
源代码7 项目: incubator-gobblin   文件: GobblinHelixTask.java
@Override
public TaskResult run() {
  this.taskMetrics.helixTaskTotalRunning.incrementAndGet();
  long startTime = System.currentTimeMillis();
  log.info("Actual task {} started. [{} {}]", this.taskId, this.applicationName, this.instanceName);
  try (Closer closer = Closer.create()) {
    closer.register(MDC.putCloseable(ConfigurationKeys.JOB_NAME_KEY, this.jobName));
    closer.register(MDC.putCloseable(ConfigurationKeys.JOB_KEY_KEY, this.jobKey));
    this.task.run();
    log.info("Actual task {} completed.", this.taskId);
    this.taskMetrics.helixTaskTotalCompleted.incrementAndGet();
    return new TaskResult(TaskResult.Status.COMPLETED, "");
  } catch (InterruptedException ie) {
    Thread.currentThread().interrupt();
    log.error("Actual task {} interrupted.", this.taskId);
    this.taskMetrics.helixTaskTotalFailed.incrementAndGet();
    return new TaskResult(TaskResult.Status.CANCELED, "");
  } catch (TaskCreationException te) {
    eventBus.post(createTaskCreationEvent("Task Execution"));
    log.error("Actual task {} failed in creation due to {}, will request new container to schedule it",
        this.taskId, te.getMessage());
    this.taskMetrics.helixTaskTotalCancelled.incrementAndGet();
    return new TaskResult(TaskResult.Status.FAILED, Throwables.getStackTraceAsString(te));
  } catch (Throwable t) {
    log.error("Actual task {} failed due to {}", this.taskId, t.getMessage());
    this.taskMetrics.helixTaskTotalCancelled.incrementAndGet();
    return new TaskResult(TaskResult.Status.FAILED, Throwables.getStackTraceAsString(t));
  } finally {
    this.taskMetrics.helixTaskTotalRunning.decrementAndGet();
    this.taskMetrics.updateTimeForTaskExecution(startTime);
  }
}
 
源代码8 项目: buck   文件: IdbRunTestsStep.java
@Override
public void run() {
  try (InputStreamReader stderrReader =
          new InputStreamReader(launchedProcess.getStderr(), StandardCharsets.UTF_8);
      BufferedReader bufferedStderrReader = new BufferedReader(stderrReader)) {
    stderr = CharStreams.toString(bufferedStderrReader).trim();
  } catch (IOException e) {
    stderr = Throwables.getStackTraceAsString(e);
  }
}
 
源代码9 项目: buck   文件: ThrowableConsoleEvent.java
private static String combineThrowableAndMessage(Throwable throwable, String message) {
  String desc = message + System.lineSeparator() + throwable.getClass().getCanonicalName();
  if (throwable.getMessage() != null) {
    desc += ": " + throwable.getMessage();
  }
  desc += System.lineSeparator() + Throwables.getStackTraceAsString(throwable);
  return desc;
}
 
源代码10 项目: linden   文件: CoreLindenCluster.java
@Override
public LindenResult search(final LindenSearchRequest request) throws IOException {
  if (cache != null) {
    try {
      LindenResult result = cache.get(request);
      if (!result.isSuccess()) {
        cache.invalidate(request);
      }
      return result;
    } catch (ExecutionException e) {
      throw new IOException(Throwables.getStackTraceAsString(e));
    }
  }
  return coreSearch(request);
}
 
源代码11 项目: linden   文件: LindenJiebaAnalyzer.java
@Override
public final boolean incrementToken() throws IOException {
  clearAttributes();
  if (tokens.isEmpty()) {
    try {
      currentPos = 0;
      BufferedReader br = new BufferedReader(input);
      String content = br.readLine();
      inputLength = content.length();
      tokens = segmenter.parse(content);
    } catch (Exception e) {
      throw new IOException(Throwables.getStackTraceAsString(e));
    }
  }
  if (!tokens.isEmpty()) {
    if (currentPos != tokens.size()) {
      LindenSegmenter.Term word = tokens.get(currentPos);
      if (word != null) {
        ++currentPos;
        termAtt.copyBuffer(word.value.toCharArray(), 0, word.value.length());
        offsetAtt.setOffset(word.startOffset, word.endOffset);
        return true;
      }
    } else {
      currentPos = 0;
      tokens.clear();
    }
  }
  return false;
}
 
源代码12 项目: graviteeio-access-management   文件: PolicyChain.java
@Override
public void doNext(Request request, Response response) {
    if (policyIterator.hasNext()) {
        Policy policy = policyIterator.next();
        try {
            if (policy.isRunnable()) {
                // enhance execution context with policy metadata
                if (policy.metadata() != null) {
                    policy.metadata().forEach(executionContext::setAttribute);
                }
                execute(
                        policy,
                        this,
                        executionContext.request(),
                        executionContext.response(),
                        executionContext);
            } else {
                doNext(executionContext.request(), executionContext.response());
            }
        } catch (Exception ex) {
            final String message = "An error occurs in policy[" + policy.id()+"] error["+ Throwables.getStackTraceAsString(ex)+"]";
            LOGGER.error(message);
            request.metrics().setMessage(message);
            if (errorHandler != null) {
                errorHandler.handle(new PolicyChainProcessorFailure(PolicyResult.failure(
                        GATEWAY_POLICY_INTERNAL_ERROR_KEY, ex.getMessage())));
            }
        }
    } else {
        next.handle(executionContext);
    }

}
 
源代码13 项目: beihu-boot   文件: ServiceExceptionHandler.java
@ExceptionHandler(IllegalArgumentException.class)
protected JsonResponse handleIllegalArgumentError(IllegalArgumentException e) {
	String stackTraceAsString = Throwables.getStackTraceAsString(e);
	LOGGER.error("【ServiceExceptionHandler - ServiceException】\r\n [{}]", stackTraceAsString);
	return BasicResponse.error(BasicServiceCode.BAD_REQUEST);
}
 
源代码14 项目: pravega   文件: PravegaRequestProcessor.java
private Void handleException(long requestId, String segment, long offset, String operation, Throwable u) {
    if (u == null) {
        IllegalStateException exception = new IllegalStateException("No exception to handle.");
        log.error(requestId, "Error (Segment = '{}', Operation = '{}')", segment, operation, exception);
        throw exception;
    }

    u = Exceptions.unwrap(u);
    String clientReplyStackTrace = replyWithStackTraceOnError ? Throwables.getStackTraceAsString(u) : EMPTY_STACK_TRACE;
    final Consumer<Throwable> failureHandler = t -> {
        log.error(requestId, "Error (Segment = '{}', Operation = '{}')", segment, "handling result of " + operation, t);
        connection.close();
    };

    if (u instanceof StreamSegmentExistsException) {
        log.info(requestId, "Segment '{}' already exists and cannot perform operation '{}'.",
                 segment, operation);
        invokeSafely(connection::send, new SegmentAlreadyExists(requestId, segment, clientReplyStackTrace), failureHandler);

    } else if (u instanceof StreamSegmentNotExistsException) {
        log.warn(requestId, "Segment '{}' does not exist and cannot perform operation '{}'.",
                 segment, operation);
        invokeSafely(connection::send, new NoSuchSegment(requestId, segment, clientReplyStackTrace, offset), failureHandler);
    } else if (u instanceof StreamSegmentSealedException) {
        log.info(requestId, "Segment '{}' is sealed and cannot perform operation '{}'.",
                 segment, operation);
        invokeSafely(connection::send, new SegmentIsSealed(requestId, segment, clientReplyStackTrace, offset), failureHandler);
    } else if (u instanceof ContainerNotFoundException) {
        int containerId = ((ContainerNotFoundException) u).getContainerId();
        log.warn(requestId, "Wrong host. Segment = '{}' (Container {}) is not owned. Operation = '{}').",
                 segment, containerId, operation);
        invokeSafely(connection::send, new WrongHost(requestId, segment, "", clientReplyStackTrace), failureHandler);
    } else if (u instanceof ReadCancellationException) {
        log.info(requestId, "Sending empty response on connection {} while reading segment {} due to CancellationException.",
                connection, segment);
        invokeSafely(connection::send, new SegmentRead(segment, offset, true, false, EMPTY_BUFFER, requestId), failureHandler);
    } else if (u instanceof CancellationException) {
        log.info(requestId, "Closing connection {} while performing {} due to {}.",
                connection, operation, u.toString());
        connection.close();
    } else if (u instanceof TokenExpiredException) {
        log.warn(requestId, "Expired token during operation {}", operation);
        invokeSafely(connection::send, new AuthTokenCheckFailed(requestId, clientReplyStackTrace,
                AuthTokenCheckFailed.ErrorCode.TOKEN_EXPIRED), failureHandler);
    } else if (u instanceof TokenException) {
        log.warn(requestId, "Token exception encountered during operation {}.", operation, u);
        invokeSafely(connection::send, new AuthTokenCheckFailed(requestId, clientReplyStackTrace,
                AuthTokenCheckFailed.ErrorCode.TOKEN_CHECK_FAILED), failureHandler);
    } else if (u instanceof UnsupportedOperationException) {
        log.warn(requestId, "Unsupported Operation '{}'.", operation, u);
        invokeSafely(connection::send, new OperationUnsupported(requestId, operation, clientReplyStackTrace), failureHandler);
    } else if (u instanceof BadOffsetException) {
        BadOffsetException badOffset = (BadOffsetException) u;
        log.info(requestId, "Segment '{}' is truncated and cannot perform operation '{}' at offset '{}'", segment, operation, offset);
        invokeSafely(connection::send, new SegmentIsTruncated(requestId, segment, badOffset.getExpectedOffset(),
                                                              clientReplyStackTrace, offset), failureHandler);
    } else if (u instanceof TableSegmentNotEmptyException) {
        log.warn(requestId, "Table segment '{}' is not empty to perform '{}'.", segment, operation);
        invokeSafely(connection::send, new TableSegmentNotEmpty(requestId, segment, clientReplyStackTrace), failureHandler);
    } else if (u instanceof KeyNotExistsException) {
        log.warn(requestId, "Conditional update on Table segment '{}' failed as the key does not exist.", segment);
        invokeSafely(connection::send, new WireCommands.TableKeyDoesNotExist(requestId, segment, clientReplyStackTrace), failureHandler);
    } else if (u instanceof BadKeyVersionException) {
        log.warn(requestId, "Conditional update on Table segment '{}' failed due to bad key version.", segment);
        invokeSafely(connection::send, new WireCommands.TableKeyBadVersion(requestId, segment, clientReplyStackTrace), failureHandler);
    } else {
        logError(requestId, segment, operation, u);
        connection.close(); // Closing connection should reinitialize things, and hopefully fix the problem
        throw new IllegalStateException("Unknown exception.", u);
    }

    return null;
}
 
@Override
public String toString() {
    return Throwables.getStackTraceAsString(super.getCause());
}
 
源代码16 项目: pravega   文件: AppendProcessor.java
private void handleException(UUID writerId, long requestId, String segment, long eventNumber, String doingWhat, Throwable u) {
    if (u == null) {
        IllegalStateException exception = new IllegalStateException("No exception to handle.");
        log.error(requestId, "Append processor: Error {} on segment = '{}'", doingWhat, segment, exception);
        throw exception;
    }

    u = Exceptions.unwrap(u);
    String clientReplyStackTrace = replyWithStackTraceOnError ? Throwables.getStackTraceAsString(u) : EMPTY_STACK_TRACE;

    if (u instanceof StreamSegmentExistsException) {
        log.warn(requestId, "Segment '{}' already exists and {} cannot perform operation '{}'.", segment, writerId, doingWhat);
        connection.send(new SegmentAlreadyExists(requestId, segment, clientReplyStackTrace));
    } else if (u instanceof StreamSegmentNotExistsException) {
        log.warn(requestId, "Segment '{}' does not exist and {} cannot perform operation '{}'.", segment, writerId, doingWhat);
        connection.send(new NoSuchSegment(requestId, segment, clientReplyStackTrace, -1L));
    } else if (u instanceof StreamSegmentSealedException) {
        log.info("Segment '{}' is sealed and {} cannot perform operation '{}'.", segment, writerId, doingWhat);
        connection.send(new SegmentIsSealed(requestId, segment, clientReplyStackTrace, eventNumber));
    } else if (u instanceof ContainerNotFoundException) {
        int containerId = ((ContainerNotFoundException) u).getContainerId();
        log.warn(requestId, "Wrong host. Segment '{}' (Container {}) is not owned and {} cannot perform operation '{}'.",
                segment, containerId, writerId, doingWhat);
        connection.send(new WrongHost(requestId, segment, "", clientReplyStackTrace));
    } else if (u instanceof BadAttributeUpdateException) {
        log.warn(requestId, "Bad attribute update by {} on segment {}.", writerId, segment, u);
        connection.send(new InvalidEventNumber(writerId, requestId, clientReplyStackTrace));
        connection.close();
    } else if (u instanceof TokenExpiredException) {
        log.warn(requestId, "Token expired for writer {} on segment {}.", writerId, segment, u);
        connection.close();
    } else if (u instanceof TokenException) {
        log.warn(requestId, "Token check failed or writer {} on segment {}.", writerId, segment, u);
        connection.send(new WireCommands.AuthTokenCheckFailed(requestId, clientReplyStackTrace,
                WireCommands.AuthTokenCheckFailed.ErrorCode.TOKEN_CHECK_FAILED));
    } else if (u instanceof UnsupportedOperationException) {
        log.warn(requestId, "Unsupported Operation '{}'.", doingWhat, u);
        connection.send(new OperationUnsupported(requestId, doingWhat, clientReplyStackTrace));
    } else if (u instanceof CancellationException) {
        // Cancellation exception is thrown when the Operation processor is shutting down.
        log.info("Closing connection '{}' while performing append on Segment '{}' due to {}.", connection, segment, u.toString());
        connection.close();
    } else {
        logError(segment, u);
        connection.close(); // Closing connection should reinitialize things, and hopefully fix the problem
    }
}
 
@Override
protected void uncaughtExceptionInSwingEDT(Thread thread,
                                           Throwable throwable) {
  String stackTraceAsString = Throwables.getStackTraceAsString(throwable);
  if (caughtStackTraces.contains(stackTraceAsString)) {
    LOGGER.info("Not sending the same error report twice");
    return;
  }
  caughtStackTraces.add(stackTraceAsString);
  JPanel message = new JPanel(new BorderLayout());
  message.add(new JLabel("Error in thread " + thread.getName()), BorderLayout.NORTH);

  String stackTrace = getStackTrace(throwable);
  JTextArea textArea = new JTextArea(10, 70);
  textArea.setText(stackTrace);
  textArea.setCaretPosition(0);
  message.add(new JScrollPane(textArea));

  JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);

  Map<String, String> errorReportData = generateReportData(thread, throwable, otrosApplication);
  JComponent jComponent = createDialogView();
  String[] options = {"Send", "Do not send"};
  int sendReport = JOptionPane.showOptionDialog(
    otrosApplication.getApplicationJFrame(),
    jComponent,
    "Send error report confirmation",
    JOptionPane.YES_NO_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    Icons.MEGAPHONE_24,
    options, options[0]);
  errorReportData.put("USER:comment", commentTextArea.getText());

  if (sendReport == JOptionPane.YES_OPTION) {
    DataConfiguration c = otrosApplication.getConfiguration();
    c.setProperty(ConfKeys.HTTP_PROXY_USE, checkBoxUseProxy.isSelected());
    c.setProperty(ConfKeys.HTTP_PROXY_HOST, proxyTf.getText());
    c.setProperty(ConfKeys.HTTP_PROXY_PORT, proxyPortModel.getNumber().intValue());
    c.setProperty(ConfKeys.HTTP_PROXY_USER, proxyUser.getText());
    sendReportInNewBackground(errorReportData);
  } else {
    LOGGER.info("Not sending error report");
  }

  logErrorReport(errorReportData);

}
 
源代码18 项目: ldp4j   文件: Diagnosis.java
static Diagnosis create(Throwable rootCause) {
	return new Diagnosis(
			Status.INTERNAL_SERVER_ERROR.getStatusCode(),
			Throwables.getStackTraceAsString(rootCause),
			true);
}
 
源代码19 项目: onboard   文件: GlobalControllerExceptionHandler.java
public ErrorInfo(int code, String url, Exception ex) {
    this.code = code;
    this.url = url;
    this.ex = Throwables.getStackTraceAsString(ex);
}
 
源代码20 项目: j360-dubbo-app-all   文件: ExceptionUtil.java
/**
 * 将StackTrace[]转换为String, 供Logger或e.printStackTrace()外的其他地方使用.
 * 
 * @see Throwables#getStackTraceAsString(Throwable)
 */
public static String stackTraceText(Throwable t) {
	return Throwables.getStackTraceAsString(t);
}