Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Getting Stack Trace From an Exception in Java [Snippet]

DZone's Guide to

Getting Stack Trace From an Exception in Java [Snippet]

This code allows you to extract stack trace, providing useful information when you're working on a platform when you can deploy custom Java code.

· Performance Zone
Free Resource

Learn how real real-time monitoring is critical for DevOps. Because you can't build what you can't see.

Extracting stack trace from an exception could provide useful information, especially when you work on platforms where you can deploy custom Java code, exception handling is done by the platform, and exceptions from your custom-written Java code are masked by default platform exceptions.

Typical messages you see from these exceptions logged or shown on the platform UI would be: "Unable to Execute API," "Something went wrong," etc.

Catching these custom exceptions in your own Java code and logging them should be good practice to solve the above-mentioned problem.

public static void extractStackTrace(Exception exception, Logger _logger) {

 StackTraceElement[] elements = exception.getStackTrace();
 String trace = null;
 for (StackTraceElement element: elements) {
  trace = (trace == null) ? element.toString() : trace + ",\n" + element.toString();
 }
 _logger.error(log);
}


This way you have access to stack trace for debugging in the logs, while the platform where you deploy your code does not give you this information.

Get real-time alerts and visualizations across your cloud infrastructure for real real-time cloud monitoring. Try it FREE now

Topics:
java ,stack traces ,logging ,exceptions ,performance

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}