下面列出了com.google.common.base.Throwables#getStackTraceAsString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
@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;
}
@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));
}
}
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;
}
@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);
}
}
@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);
}
}
@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);
}
}
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;
}
@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);
}
@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;
}
@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);
}
}
@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);
}
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());
}
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);
}
static Diagnosis create(Throwable rootCause) {
return new Diagnosis(
Status.INTERNAL_SERVER_ERROR.getStatusCode(),
Throwables.getStackTraceAsString(rootCause),
true);
}
public ErrorInfo(int code, String url, Exception ex) {
this.code = code;
this.url = url;
this.ex = Throwables.getStackTraceAsString(ex);
}
/**
* 将StackTrace[]转换为String, 供Logger或e.printStackTrace()外的其他地方使用.
*
* @see Throwables#getStackTraceAsString(Throwable)
*/
public static String stackTraceText(Throwable t) {
return Throwables.getStackTraceAsString(t);
}