下面列出了org.apache.commons.lang.exception.ExceptionUtils#getStackTrace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unchecked")
public static JSONObject generateErrorMessage(String message, Exception e)
{
JSONObject error_message = new JSONObject();
/*
* Save full stack trace in object.
*/
String stackTrace = ExceptionUtils.getStackTrace(e);
String exception = e.toString();
error_message.put("time", System.currentTimeMillis());
try {
error_message.put("hostname", InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
error_message.put("message", message);
error_message.put("exception", exception);
error_message.put("stack", stackTrace);
return error_message;
}
@Override
public void setErrorStatus(final String indexerProcessId, Throwable error) {
final String stackTrace = ExceptionUtils.getStackTrace(error);
try {
zk.retryOperation(new ZooKeeperOperation<Integer>() {
@Override
public Integer execute() throws KeeperException, InterruptedException {
zk.setData(indexerProcessId, Bytes.toBytes(stackTrace), -1);
return 0;
}
});
} catch (Exception e) {
throw new RuntimeException("Error while setting error status on indexer node " + indexerProcessId, e);
}
}
public void disconnect() throws IOException {
if (connected.compareAndSet(true, false)) {
try {
if (channel != null) {
channel.close();
}
logger.info("disConnect MysqlConnection to " + address);
} catch (Exception e) {
throw new IOException("disconnect " + this.address + " failure:" + ExceptionUtils.getStackTrace(e));
}
} else {
logger.info("the channel " + address + " is not connected");
}
}
/**
* Tests that the getCredentials won't leak credentials data if the response from ECS is corrupted.
*/
@Test
public void getCredentialsWithCorruptResponseDoesNotIncludeCredentialsInExceptionMessage() {
stubForCorruptedSuccessResponse();
try {
containerCredentialsProvider.getCredentials();
Assert.fail();
} catch (Exception e) {
String stackTrace = ExceptionUtils.getStackTrace(e);
Assert.assertFalse(stackTrace.contains("ACCESS_KEY_ID"));
Assert.assertFalse(stackTrace.contains("SECRET_ACCESS_KEY"));
Assert.assertFalse(stackTrace.contains("TOKEN_TOKEN_TOKEN"));
}
}
void failSafe(Throwable t) {
String msg = "Unexpected error: " + t.getMessage() + "\n" + ExceptionUtils.getStackTrace(t);
consoleWriter.newLine().fg(Ansi.Color.YELLOW).a(msg).println(2);
logger.error("Unexpected error", t);
consoleWriter.fg(Ansi.Color.GREEN).a("Failing safe...").println();
tryToSendFailSafeNotification();
}
/**
* Sends out final events for task failure.
* @param taskAttemptID
* @param isKilled
* @param taskFailureType
* @param t
* @param diagnostics
* @param srcMeta
* @return
* @throws IOException
* indicates an RPC communication failure.
* @throws TezException
* indicates an exception somewhere in the AM.
*/
private boolean taskTerminated(TezTaskAttemptID taskAttemptID, boolean isKilled, TaskFailureType taskFailureType,
Throwable t, String diagnostics,
EventMetaData srcMeta) throws IOException, TezException {
// Ensure only one final event is ever sent.
if (!finalEventQueued.getAndSet(true)) {
List<TezEvent> tezEvents = new ArrayList<TezEvent>();
if (diagnostics == null) {
diagnostics = ExceptionUtils.getStackTrace(t);
} else {
diagnostics = diagnostics + ":" + ExceptionUtils.getStackTrace(t);
}
if (isKilled) {
tezEvents.add(new TezEvent(new TaskAttemptKilledEvent(diagnostics),
srcMeta == null ? updateEventMetadata : srcMeta));
} else {
tezEvents.add(new TezEvent(new TaskAttemptFailedEvent(diagnostics,
taskFailureType),
srcMeta == null ? updateEventMetadata : srcMeta));
}
try {
tezEvents.add(new TezEvent(getStatusUpdateEvent(true), updateEventMetadata));
} catch (Exception e) {
// Counter may exceed limitation
LOG.warn("Error when get constructing TaskStatusUpdateEvent. Not sending it out");
}
return !heartbeat(tezEvents).shouldDie;
} else {
LOG.warn("A final task state event has already been sent. Not sending again");
return askedToDie.get();
}
}
/**
* Passes all the records through the function {@link #parseEventLine(String) parseEventLine}
* and returns a map which contains keys and values for all the records
*
* @param records records of a single event
* @return map of key values
*/
private Map<String, String> getEventMap(Set<String> records) throws Exception{
try{
Map<String, String> eventMap = new HashMap<String, String>();
for(String record : records){
eventMap.putAll(parseEventLine(record));
}
return eventMap;
}catch(Exception e){
throw new MalformedAuditDataException(e.getMessage()+
" ["+ExceptionUtils.getStackTrace(e)+"] ", String.valueOf(records));
}
}
@SuppressWarnings({"unchecked"})
private void addStacktrace(JSONObject errorMessage) {
if (throwable != null) {
String stackTrace = ExceptionUtils.getStackTrace(throwable);
String exception = throwable.toString();
errorMessage.put(ErrorFields.EXCEPTION.getName(), exception);
errorMessage.put(ErrorFields.STACK.getName(), stackTrace);
}
}
/**
* Run commands as the CommandsSender, replacing all tags with the relevant values.
* @param sender The sender that should perform the command
* @param commands A list of the commands to run (without slash and with tags)
*/
public void runCommands(CommandSender sender, List<String> commands) {
if(commands == null || commands.isEmpty()) {
return;
}
for(String command : commands) {
if(command == null || command.isEmpty()) {
continue;
}
// It is not ideal we have to disable language replacements here, but otherwise giving language variables
// to '/areashop message' by a command in the config gets replaced and messes up the fancy formatting.
command = Message.fromString(command).replacements(this).noLanguageReplacements().getSingle();
boolean result;
String error = null;
String stacktrace = null;
try {
result = plugin.getServer().dispatchCommand(sender, command);
} catch(CommandException e) {
result = false;
error = e.getMessage();
stacktrace = ExceptionUtils.getStackTrace(e);
}
boolean printed = false;
if(!result) {
printed = true;
if(error != null) {
AreaShop.warn("Command execution failed, command=" + command + ", error=" + error + ", stacktrace:");
AreaShop.warn(stacktrace);
AreaShop.warn("--- End of stacktrace ---");
} else {
AreaShop.warn("Command execution failed, command=" + command);
}
}
if(!printed) {
AreaShop.debug("Command run, executor=" + sender.getName() + ", command=" + command);
}
}
}
private String recoverSuccessTaskAttempt(TaskImpl task) {
// Found successful attempt
// Recover data
String errorMsg = null;
if (task.getVertex().getOutputCommitters() != null
&& !task.getVertex().getOutputCommitters().isEmpty()) {
for (Entry<String, OutputCommitter> entry
: task.getVertex().getOutputCommitters().entrySet()) {
LOG.info("Recovering data for task from previous DAG attempt"
+ ", taskId=" + task.getTaskId()
+ ", output=" + entry.getKey());
OutputCommitter committer = entry.getValue();
if (!committer.isTaskRecoverySupported()) {
errorMsg = "Task recovery not supported by committer"
+ ", failing task attempt";
LOG.info(errorMsg
+ ", taskId=" + task.getTaskId()
+ ", attemptId=" + task.successfulAttempt
+ ", output=" + entry.getKey());
break;
}
try {
committer.recoverTask(task.getTaskId().getId(),
task.appContext.getApplicationAttemptId().getAttemptId()-1);
} catch (Exception e) {
errorMsg = "Task recovery failed by committer: "
+ ExceptionUtils.getStackTrace(e);
LOG.warn("Task recovery failed by committer"
+ ", taskId=" + task.getTaskId()
+ ", attemptId=" + task.successfulAttempt
+ ", output=" + entry.getKey(), e);
break;
}
}
}
return errorMsg;
}
protected static void handleError(Throwable e, Response response, HttpStatus status) throws IOException
{
String configJson = e.getMessage()==null?ExceptionUtils.getStackTrace(e):e.getMessage();
response.setContentLength(configJson.length());
response.getWriter().write(configJson);
response.setStatus(status==null?HttpStatus.INTERNAL_SERVER_ERROR_500:status);
if(status==null)e.printStackTrace();
}
protected static void handleErrorJson(Throwable e, Response response, HttpStatus status) throws IOException
{
String configJson = e.getMessage()==null?ExceptionUtils.getStackTrace(e):e.getMessage();
response.setContentType(MediaType.APPLICATION_XML);
response.setContentLength(configJson.length());
response.getWriter().write(configJson);
response.setStatus(status==null?HttpStatus.INTERNAL_SERVER_ERROR_500:status);
if(status==null)e.printStackTrace();
}
public static void sendError(Throwable exception, Request request) {
setContentType("text/html");
setSubject("An OpenSeedbox error occured!");
addRecipient(Config.getErrorEmailAddress());
setFrom(Config.getErrorFromEmailAddress());
String stackTrace = ExceptionUtils.getStackTrace(exception);
send("mails/sendError", exception, stackTrace, request);
}
public static void nodeDown(Node node, Throwable exactError) {
setContentType("text/html");
setSubject("Node '" + node.getName() + "' is down!");
addRecipient(Config.getErrorEmailAddress());
setFrom(Config.getErrorFromEmailAddress());
String stackTrace = "Node wont respond to pings.";
if (exactError != null) {
stackTrace = ExceptionUtils.getStackTrace(exactError);
}
String status = "down";
send("mails/nodeDown", node, stackTrace, status);
}
@SuppressWarnings("unchecked")
public synchronized void launch(ContainerLaunchRequest event) {
LOG.info("Launching " + event.getContainerId());
if(this.state == ContainerState.KILLED_BEFORE_LAUNCH) {
state = ContainerState.DONE;
sendContainerLaunchFailedMsg(event.getContainerId(),
"Container was killed before it was launched");
return;
}
ContainerManagementProtocolProxyData proxy = null;
try {
proxy = getCMProxy(containerID, containerMgrAddress,
containerToken);
// Construct the actual Container
ContainerLaunchContext containerLaunchContext =
event.getContainerLaunchContext();
// Now launch the actual container
StartContainerRequest startRequest = Records
.newRecord(StartContainerRequest.class);
startRequest.setContainerToken(event.getContainerToken());
startRequest.setContainerLaunchContext(containerLaunchContext);
StartContainersResponse response =
proxy.getContainerManagementProtocol().startContainers(
StartContainersRequest.newInstance(
Collections.singletonList(startRequest)));
if (response.getFailedRequests() != null
&& !response.getFailedRequests().isEmpty()) {
throw response.getFailedRequests().get(containerID).deSerialize();
}
// after launching, send launched event to task attempt to move
// it from ASSIGNED to RUNNING state
getContext().containerLaunched(containerID);
this.state = ContainerState.RUNNING;
int shufflePort = TezRuntimeUtils.INVALID_PORT;
Map<String, java.nio.ByteBuffer> servicesMetaData = response.getAllServicesMetaData();
if (servicesMetaData != null) {
String auxiliaryService = conf.get(TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID,
TezConfiguration.TEZ_AM_SHUFFLE_AUXILIARY_SERVICE_ID_DEFAULT);
ByteBuffer portInfo = servicesMetaData.get(auxiliaryService);
if (portInfo != null) {
DataInputByteBuffer in = new DataInputByteBuffer();
in.reset(portInfo);
shufflePort = in.readInt();
} else {
LOG.warn("Shuffle port for {} is not present is the services metadata response", auxiliaryService);
}
} else {
LOG.warn("Shuffle port cannot be found since services metadata response is missing");
}
if (deletionTracker != null) {
deletionTracker.addNodeShufflePort(event.getNodeId(), shufflePort);
}
} catch (Throwable t) {
String message = "Container launch failed for " + containerID + " : "
+ ExceptionUtils.getStackTrace(t);
this.state = ContainerState.FAILED;
sendContainerLaunchFailedMsg(containerID, message);
} finally {
if (proxy != null) {
cmProxy.mayBeCloseProxy(proxy);
}
}
}
/**
* Handles processing with referrals without ManageDsaIT decorator.
*/
public void handleException( LdapSession session, ResultResponseRequest req, Exception e )
{
LdapResult result = req.getResultResponse().getLdapResult();
Exception cause = null;
/*
* Set the result code or guess the best option.
*/
ResultCodeEnum code;
if ( e instanceof CursorClosedException )
{
cause = ( Exception ) ( ( CursorClosedException ) e ).getCause();
if ( cause == null )
{
cause = e;
}
}
else
{
cause = e;
}
if ( cause instanceof LdapOperationException )
{
code = ( ( LdapOperationException ) cause ).getResultCode();
}
else
{
code = ResultCodeEnum.getBestEstimate( cause, req.getType() );
}
result.setResultCode( code );
/*
* Setup the error message to put into the request and put entire
* exception into the message if we are in debug mode. Note we
* embed the result code name into the message.
*/
String msg = code.toString() + ": failed for " + req + ": " + cause.getLocalizedMessage();
if ( IS_DEBUG )
{
LOG.debug( msg, cause );
msg += ":\n" + ExceptionUtils.getStackTrace( cause );
}
result.setDiagnosticMessage( msg );
if ( cause instanceof LdapOperationException )
{
LdapOperationException ne = ( LdapOperationException ) cause;
// Add the matchedDN if necessary
boolean setMatchedDn = code == ResultCodeEnum.NO_SUCH_OBJECT || code == ResultCodeEnum.ALIAS_PROBLEM
|| code == ResultCodeEnum.INVALID_DN_SYNTAX || code == ResultCodeEnum.ALIAS_DEREFERENCING_PROBLEM;
if ( ( ne.getResolvedDn() != null ) && setMatchedDn )
{
result.setMatchedDn( ne.getResolvedDn() );
}
}
session.getIoSession().write( req.getResultResponse() );
}
/**
* Handles processing with referrals without ManageDsaIT decorator.
*/
public void handleException( LdapSession session, ResultResponseRequest req, Exception e )
{
LdapResult result = req.getResultResponse().getLdapResult();
Exception cause = null;
/*
* Set the result code or guess the best option.
*/
ResultCodeEnum code;
if ( e instanceof CursorClosedException )
{
cause = ( Exception ) ( ( CursorClosedException ) e ).getCause();
if ( cause == null )
{
cause = e;
}
}
else
{
cause = e;
}
if ( cause instanceof LdapOperationException )
{
code = ( ( LdapOperationException ) cause ).getResultCode();
}
else
{
code = ResultCodeEnum.getBestEstimate( cause, req.getType() );
}
result.setResultCode( code );
/*
* Setup the error message to put into the request and put entire
* exception into the message if we are in debug mode. Note we
* embed the result code name into the message.
*/
String msg = code.toString() + ": failed for " + req + ": " + cause.getLocalizedMessage();
if ( IS_DEBUG )
{
LOG.debug( msg, cause );
msg += ":\n" + ExceptionUtils.getStackTrace( cause );
}
result.setDiagnosticMessage( msg );
if ( cause instanceof LdapOperationException )
{
LdapOperationException ne = ( LdapOperationException ) cause;
// Add the matchedDN if necessary
boolean setMatchedDn = code == ResultCodeEnum.NO_SUCH_OBJECT || code == ResultCodeEnum.ALIAS_PROBLEM
|| code == ResultCodeEnum.INVALID_DN_SYNTAX || code == ResultCodeEnum.ALIAS_DEREFERENCING_PROBLEM;
if ( ( ne.getResolvedDn() != null ) && setMatchedDn )
{
result.setMatchedDn( ne.getResolvedDn() );
}
}
session.getIoSession().write( req.getResultResponse() );
}
@Override
public void onTestFailure(ITestResult testResult) {
ReportiumClient client = getReportClient();
if (null != client) {
String failMsg = "";
List<CheckpointResultBean> checkpointsList = TestBaseProvider.instance().get().getCheckPointResults();
for (CheckpointResultBean result : checkpointsList) {
if (result.getType().equals(MessageTypes.TestStepFail.toString())) {
failMsg += "Step:" + result.getMessage() + " failed" + "\n";
// List<CheckpointResultBean> subList = result.getSubCheckPoints();
// for (CheckpointResultBean sub : subList) {
// if (sub.getType().equals(MessageTypes.Fail.toString())){
// failMsg += sub.getMessage() + "\n";
// }
// }
}
}
if (testResult.getThrowable() == null) {
client.testStop(TestResultFactory.createFailure(failMsg.isEmpty() ? "An error occurred" : failMsg,
new Exception(
"There was some validation failure in the scenario which did not provide any throwable object.")));
} else {
ExceptionUtils.getStackTrace(testResult.getThrowable());
String actualExceptionMessage = testResult.getThrowable().toString();
Messages message = parseFailureJsonFile(actualExceptionMessage);
if (message != null) {
String customError = message.getCustomError();
List<String> customFields = ListUtils.emptyIfNull(message.getCustomFields());
List<String> tags = ListUtils.emptyIfNull(message.getTags());
String fileLoc = message.getJsonFile();
ArrayList<CustomField> cfc = new ArrayList<CustomField>();
for (String customField : customFields) {
try {
cfc.add(new CustomField(
customField.split(getBundle().getString("custom.field.delimiter", "-"))[0],
customField.split(getBundle().getString("custom.field.delimiter", "-"))[1]));
} catch (Exception ex) {
throw new NullPointerException(
"Custom field key/value pair not delimited properly in failure reason json file: "
+ fileLoc
+ ". Example of proper default usage: Developer-Jeremy. Check application properties custom.field.delimiter for custom values that may have been set.");
}
}
ArrayList<String> tagsFinal = new ArrayList<String>();
for (String tag : tags) {
tagsFinal.add(tag);
}
Builder testContext = new TestContext.Builder();
if (cfc.size() > 0) {
testContext.withCustomFields(cfc);
}
if (tagsFinal.size() > 0) {
testContext.withTestExecutionTags(tagsFinal);
}
TestResult reportiumResult = TestResultFactory.createFailure(
failMsg.isEmpty() ? "An error occurred" : failMsg, testResult.getThrowable(), customError);
client.testStop(reportiumResult, testContext.build());
} else {
client.testStop(TestResultFactory.createFailure(failMsg.isEmpty() ? "An error occurred" : failMsg,
testResult.getThrowable()));
}
}
logTestEnd(testResult);
tearIt(testResult);
}
}
public String getTraceMessage() {
if(traceMessage == null && getCause() != null){
this.traceMessage = ExceptionUtils.getStackTrace(getCause());
}
return traceMessage;
}
/**
* Format the available parameters into a XML-message.
*
* Override this method in descender-classes to obtain the required behaviour.
*/
@Override
public String format(String errorMessage, Throwable t, INamedObject location, Message originalMessage, String messageId, long receivedTime) {
String details = null;
errorMessage = getErrorMessage(errorMessage, t);
if (t != null) {
details = ExceptionUtils.getStackTrace(t);
}
String originator = AppConstants.getInstance().getProperty("application.name")+" "+ AppConstants.getInstance().getProperty("application.version");
// Build a Base xml
XmlBuilder errorXml = new XmlBuilder("errorMessage");
errorXml.addAttribute("timestamp", new Date().toString());
errorXml.addAttribute("originator", originator);
errorXml.addAttribute("message", XmlUtils.replaceNonValidXmlCharacters(errorMessage));
if (location != null) {
XmlBuilder locationXml = new XmlBuilder("location");
locationXml.addAttribute("class", location.getClass().getName());
locationXml.addAttribute("name", location.getName());
errorXml.addSubElement(locationXml);
}
if (details != null && !details.equals("")) {
XmlBuilder detailsXml = new XmlBuilder("details");
// detailsXml.setCdataValue(details);
detailsXml.setValue(XmlUtils.replaceNonValidXmlCharacters(details), true);
errorXml.addSubElement(detailsXml);
}
XmlBuilder originalMessageXml = new XmlBuilder("originalMessage");
originalMessageXml.addAttribute("messageId", messageId);
if (receivedTime != 0) {
originalMessageXml.addAttribute("receivedTime", new Date(receivedTime).toString());
}
// originalMessageXml.setCdataValue(originalMessage);
try {
originalMessageXml.setValue(originalMessage.asString(), true);
} catch (IOException e) {
log.warn("Could not convert originalMessage for messageId ["+messageId+"]",e);
originalMessageXml.setValue(originalMessage.toString(), true);
}
errorXml.addSubElement(originalMessageXml);
return errorXml.toXML();
}