Get detail messages of chained exceptions Java - java

I'd like to know how I could throw a "final" Exception, containing a detailed message with all the detailed messages of a number of chained exceptions.
For example suppose a code like this:
try {
try {
try {
try {
//Some error here
} catch (Exception e) {
throw new Exception("FIRST EXCEPTION", e);
}
} catch (Exception e) {
throw new Exception("SECOND EXCEPTION", e);
}
} catch (Exception e) {
throw new Exception("THIRD EXCEPTION", e);
}
} catch (Exception e) {
String allMessages = //all the messages
throw new Exception(allMessages, e);
}
I'm not interested in the full stackTrace, but only in the messages, I wrote. I mean, I'd like to have a result like this:
java.lang.Exception: THIRD EXCEPTION + SECOND EXCEPTION + FIRST EXCEPTION

I think what you need is:
public static List<String> getExceptionMessageChain(Throwable throwable) {
List<String> result = new ArrayList<String>();
while (throwable != null) {
result.add(throwable.getMessage());
throwable = throwable.getCause();
}
return result; //["THIRD EXCEPTION", "SECOND EXCEPTION", "FIRST EXCEPTION"]
}

you can better use it this way, merge the message() of previous Exception with the message() of new Exception you are throwing:
} catch (Exception e) {
throw new Exception("FIRST EXCEPTION" + e.getMessage(), e);
}

Cycle through the exception cause and append the message in each exception.
try
{
try
{
try
{
try
{
throw new RuntimeException("Message");
}
catch (Exception e)
{
throw new Exception("FIRST EXCEPTION", e);
}
}
catch (Exception e)
{
throw new Exception("SECOND EXCEPTION", e);
}
}
catch (Exception e)
{
throw new Exception("THIRD EXCEPTION", e);
}
}
catch (Exception e)
{
String message = e.getMessage();
Throwable inner = null;
Throwable root = e;
while ((inner = root.getCause()) != null)
{
message += " " + inner.getMessage();
root = inner;
}
System.out.println(message);
}
Which prints
THIRD EXCEPTION SECOND EXCEPTION FIRST EXCEPTION Message

You can just add the previous exception message on each exception
This is an example :
public static void main(String[] args) {
try {
try {
try {
try {
throw new Exception();
// Some error here
} catch (Exception e) {
throw new Exception("FIRST EXCEPTION", e);
}
} catch (Exception e) {
Exception e2 = new Exception("SECOND EXCEPTION + " + e.getMessage());
throw e2;
}
} catch (Exception e) {
Exception e3 = new Exception("THIRD EXCEPTION + " + e.getMessage());
throw e3;
}
} catch (Exception e) {
System.out.println(e);
}
}
The result is : java.lang.Exception: THIRD EXCEPTION + SECOND EXCEPTION + FIRST EXCEPTION

Here is a nice utility for converting chained exceptions to string:
public final class ThrowableUtil {
private ThrowableUtil() {}
public static String chainedString(#NonNull Throwable throwable) {
StringBuilder SB = new StringBuilder(throwable.toString());
while((throwable = throwable.getCause()) != null)
SB.append("\ncaused by ").append(throwable);
return SB.toString();
}
public static String chainedString(#NonNull String msg, #NonNull Throwable throwable) {
StringBuilder SB = new StringBuilder(msg);
do {
SB.append("\ncaused by ").append(throwable);
} while((throwable = throwable.getCause()) != null);
return SB.toString();
}
}
Example output:
ThrowableUtil.chainedString(e);
produces
java.io.IOException: Failed to create required video encoder
caused by java.lang.RuntimeException: Invalid mime type
Another example output:
ThrowableUtil.chainedString("Writing of media file failed", e);
produces
Writing of media file failed
caused by java.io.IOException: Failed to create required video encoder
caused by java.lang.RuntimeException: Invalid mime type

I had saved all attributes in a class object with the following example:
public List<ErrorMessage> getMessageList(Throwable throwable) {
List<ErrorMessage> errorMessageList = new ArrayList<ErrorMessage>();
while (throwable != null) {
ErrorMessage message = new ErrorMessage();
message.set_message( throwable.getMessage());
message.set_line(throwable.getStackTrace()[0].getLineNumber());
message.set_methodName(throwable.getStackTrace()[0].getMethodName());
message.set_fileName(throwable.getStackTrace()[0].getFileName() );
message.set_className(throwable.getStackTrace()[0].getClassName());
errorMessageList.add(message);
throwable = throwable.getCause();
}
return errorMessageList;
}

Maybe simpler
try {
// code that throws exception
} catch(Throwable e ) {
var messages = new ArrayList<String>();
do {
messages.add(e.getMessage());
e = e.getCause();
} while( e!= null );
var message = String.join(" -> ", messages);
System.out.println(message);
}

Related

Junit Test cases for PubSub Publish message

Facing issue while writing the Junit test cases for below code.
public String publishJSON(String json) throws InterruptedException, IOException, ExecutionException {
log.info(" Publishing payload to: "+config.getTopicId());
TopicName topicName=TopicName.of(config.getPubsubProjectId(),config.getTopicId());
Publisher publisher=null;
try {
publisher =
Publisher.newBuilder(topicName)
.build();
ByteString data = ByteString.copyFromUtf8(json);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
String messageId = messageIdFuture.get();
log.info("Published message ID: " + messageId);
return messageId;
} catch (ExecutionException e) {
log.error("Error while publishing messsage" + e.getMessage());
throw e;
} catch (IOException e) {
log.error( "PubSub exception "+ e.getMessage());
throw e;
} catch (InterruptedException e) {
log.error("Connection making exception for PubSub" + e.getMessage());
throw e;
} catch (Exception e) {
log.error( "publishJSON Error : "+ e.getMessage());
throw e;
}
finally {
if (publisher != null) {
// When finished with the publisher, shutdown to free up resources.
publisher.shutdown();
publisher.awaitTermination(1, TimeUnit.MINUTES);
}
}
}

How to extract try catch outside method?

I have this method sendParameterValueAsMQTTMessage() which I use to publish message via MQTT on a specific topic. I am using try catch two times after another (not nested) but it still seems somewhat ugly and overcrowding the method. I read an article on clean code where Uncle Bob talks about extracting the body of try catch but I seem to not grasp it quite well or at least not in my case.
How could I get rid of the try catch in my method by extracting it outside?
public void sendParameterValueAsMQTTMessage() {
String payload = null;
try {
payload = convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC,payload,0);
try {
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
there are multiple different problems with provided code, here is how I'd refactor it:
public void sendParameterValueAsMQTTMessage() {
final String payload = tryGetPayloadAsJson();
if (payload != null) {
trySendPayloadViaMQTT(payload);
}
}
private String tryGetPayloadAsJson() {
try {
return convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
return null;
}
private void trySendPayloadViaMQTT(final String payload) {
try {
final MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC, payload, 0);
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
one thing which might be improved here based on Uncle Bob's advice is to actually move try/catch outside of trySendPayloadViaMQTT, like this:
public void sendParameterValueAsMQTTMessage() {
final String payload = tryGetPayloadAsJson();
if (payload != null) {
trySendPayloadViaMQTT(payload);
}
}
private String tryGetPayloadAsJson() {
try {
return convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
return null;
}
private void trySendPayloadViaMQTT(final String payload) {
try {
sendPayloadViaMQTT(payload);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
private void sendPayloadViaMQTT(final String payload) {
final MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC, payload, 0);
this.client.publish(message);
Thread.sleep(3000);
}
you can put all of your code in just one try block and set multiple catches, when ever an exception be happened, the catch that is revelated to it will be execute, like:
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
You can use single general catch for both possible exceptions inside the method as following:
public void sendParameterValueAsMQTTMessage() {
String payload = null;
try {
payload = convertToJSONString("range", String.valueOf(range));
MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC,payload,0);
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}
public void sendParameterValueAsMQTTMessage() {
String payload = null;
try {
payload = convertToJSONString("range", String.valueOf(range));
} catch (JSONException e) {
this.logger.log(Level.ERROR, e);
}
MQTTMessage message = new MQTTMessage(MQTTTopics.RANGE_TOPIC,payload,0);
publishMessage(message); //extracted in a new method
}
public void publishMessage(MQTTMessage message){
try {
this.client.publish(message);
Thread.sleep(3000);
} catch (Exception e) {
this.logger.log(Level.ERROR, e);
}
}

Java try-with-resource implementation done by compiler

I was wondering, when exception occurs how try with resource statement manages to close resources before entering catch block.
When exception occurs execution immediately jumps to catch block. So where actually try-with-resource closes the resources.
To get better understanding of how it works I decided to see how compiler implements it. I wrote following code and and compiled it.
public class Test
{
public static void main(final String[] args) {
//I used same JDK for compilation and execution.
System.out.println("Java version: " + System.getProperty("java.version") + "\n");
try(CloseMe me = new CloseMe();
CloseMeToo meToo = new CloseMeToo()){
System.out.println("trying");
throw new Exception("try failed");
} catch(Exception e) {
System.out.println("failed");
System.out.println("\n");
System.out.println(e.getMessage());
System.out.println(e.getSuppressed()[0].getMessage());
System.out.println(e.getSuppressed()[1].getMessage());
}
}
}
class CloseMe implements AutoCloseable {
#Override
public void close() throws Exception {
System.out.println("me closing!");
throw new Exception("don't close me :o");
}
}
class CloseMeToo implements AutoCloseable {
#Override
public void close() throws Exception {
System.out.println("meToo closing!");
throw new Exception("don't close me too :O");
}
}
Output
Java version: 15.0.1
trying
meToo closing!
me closing!
failed
try failed
don't close me too :O
don't close me :o
Then I went to www.javadecompilers.com and tried the decompilers there. Two decompilers gave decent results: CFR 0.150 and Fernflower.
CFR is most readable and complete so posting it here.
public class Test
{
public static void main(final String[] args) throws Throwable{
System.out.println("Java version: " + System.getProperty("java.version") + "\n");
try {
Throwable throwable = null;
Object var2_4 = null; //<-- where this variable is used?
try {
CloseMe me = new CloseMe();
try {
CloseMeToo meToo = new CloseMeToo();
try {
System.out.println("trying");
throw new Exception("try failed");
}
catch (Throwable throwable2) {
throwable = throwable2; //<-- I put this line to make it work
if (meToo != null) {
meToo.close();
}
throw throwable2;
}
}
catch (Throwable throwable3) {
if (throwable == null) {
throwable = throwable3;
} else if (throwable != throwable3) {
throwable.addSuppressed(throwable3);
}
if (me != null) {
me.close();
}
throw throwable;
}
}
catch (Throwable throwable4) {
if (throwable == null) {
throwable = throwable4;
} else if (throwable != throwable4) {
throwable.addSuppressed(throwable4);
}
throw throwable;
}
}
catch (Exception e) {
System.out.println("failed");
System.out.println("\n");
System.out.println(e.getMessage());
System.out.println(e.getSuppressed()[0].getMessage());
System.out.println(e.getSuppressed()[1].getMessage());
}
}
}
I understand decompilers have limitations. Ideal decompiler would've given me same try-with-resource back and I wouldn't have seen these details. So it is ok.
My questions are:
In above decompiled code, variable var2_4 is unused. Also, I had to add a line to make it work like try-with-resource. I think the code is not complete. If there are any, can you add/explain missing parts?
If anyone, who understands bytecode, translate class file to exact java code would be great. Or give me pointers about where can I get the tools to do the job.
Thank you!
The behavior of try-with-resources is fully documented in the Java Language Specification, section 14.20.3. try-with-resources.
It specifically shows that the following abbreviated version of the question code:
try (CloseMe me = new CloseMe(); CloseMeToo meToo = new CloseMeToo()) {
System.out.println("trying");
} catch (Exception e) {
System.out.println("failed");
}
first gets converted to:
try {
try (CloseMe me = new CloseMe(); CloseMeToo meToo = new CloseMeToo()) {
System.out.println("trying");
}
} catch (Exception e) {
System.out.println("failed");
}
then to:
try {
final CloseMe me = new CloseMe();
Throwable #primaryExc1 = null;
try (CloseMeToo meToo = new CloseMeToo()) {
System.out.println("trying");
} catch (Throwable #t) {
#primaryExc1 = #t;
throw #t;
} finally {
if (me != null) {
if (#primaryExc1 != null) {
try {
me.close();
} catch (Throwable #suppressedExc) {
#primaryExc1.addSuppressed(#suppressedExc);
}
} else {
me.close();
}
}
}
} catch (Exception e) {
System.out.println("failed");
}
then to:
try {
final CloseMe me = new CloseMe();
Throwable #primaryExc1 = null;
try {
final CloseMeToo meToo = new CloseMeToo()
Throwable #primaryExc2 = null;
try {
System.out.println("trying");
catch (Throwable #t) {
#primaryExc2 = #t;
throw #t;
} finally {
if (meToo != null) {
if (#primaryExc2 != null) {
try {
meToo.close();
} catch (Throwable #suppressedExc) {
#primaryExc2.addSuppressed(#suppressedExc);
}
} else {
meToo.close();
}
}
}
} catch (Throwable #t) {
#primaryExc1 = #t;
throw #t;
} finally {
if (me != null) {
if (#primaryExc1 != null) {
try {
me.close();
} catch (Throwable #suppressedExc) {
#primaryExc1.addSuppressed(#suppressedExc);
}
} else {
me.close();
}
}
}
} catch (Exception e) {
System.out.println("failed");
}

Missing return statement, what i am missing

I written a method which will acknowledge the controller by returning true and false, I return true inside try if everything goes fine it will return true and I return false inside catch blocks, but still method shows me error "missing return statement" what is the best way to do it.
The below method written in java will send back the true or false to the controller.
Secondly I want to carry the exception message from here to controller, I think of returning string, is it good approach,
Kindly suggest me the best way to do the exception handling
public boolean pickSalayData(String yearMonth, String regionId, String circleId, Userdetail loginUser) throws MyExceptionHandler {
String tableSuffix = yearMonth.substring(4, 6) + yearMonth.substring(0, 4);
log.info("Pick Salary Data From ERP " + DateUtility.dateToStringDDMMMYYYY(new Date()));
List<SalaryDetailReport> detailReports = hRMSPickSalaryDataDAO.findAll(yearMonth, regionId, circleId);
TransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus trstatus = transactionManager.getTransaction(def);
try {
List<SalaryDetailReport> salaryDetailReport = null;
int countDetail = 0;
if (detailReports != null && detailReports.size() > 0) {
for (SalaryDetailReport salary : detailReports) {
try {
if (countDetail % COMMIT_COUNT == 0) {
if (salaryDetailReport != null) {
salaryDetailReportDAO.save(salaryDetailReport, tableSuffix);
reportHistoryDAO.save(salaryDetailReport, loginUser);
}
salaryDetailReport = new ArrayList<SalaryDetailReport>();
}
salaryDetailReport.add(salary);
countDetail++;
} catch (Exception e) {
log.error("Error on Save Salary Pay Head Details Data from ERP to Prayas .");
}
}
if (salaryDetailReport != null && salaryDetailReport.size() > 0) {
salaryDetailReportDAO.save(salaryDetailReport, tableSuffix);
reportHistoryDAO.save(salaryDetailReport, loginUser);
}
} else {
throw new MyExceptionHandler("No record for Save in Database from ERP.");
}
salaryDetailReportDAO.update(tableSuffix, regionId, circleId);
List<SalaryDetailReport> reports = salaryDetailReportDAO.findAll(tableSuffix, regionId, circleId);
if (reports != null && reports.size() > 0) {
for (SalaryDetailReport salaryDetail : reports) {
try {
SalaryDetail sd = new SalaryDetail();
sd.setDetailReport(salaryDetail);
salaryDetailDAO.save(sd, tableSuffix);
} catch (Exception e) {
log.error("Error occured", e);
e.printStackTrace();
throw new MyExceptionHandler(" Error :" + e.getMessage());
}
}
System.out.println("data found");
} else {
log.error("Salary Record Not Found.");
throw new MyExceptionHandler("No record Found.");
}
salaryDetailDAO.updateEarningDeduction(tableSuffix);
//salaryDetailDAO.updateEarningDeductionsInSDT();
transactionManager.commit(trstatus);
try {
hRMSPickSalaryDataDAO.update(regionId, circleId, yearMonth);
return true;
} catch (Exception ex) {
log.error("Some error : ", ex);
}
// // System.out.println("Completed =============================");
} catch (MyExceptionHandler ex) {
transactionManager.rollback(trstatus);
ex.printStackTrace();
log.error("Failed to Save Salary data :" + ex.getMessage());
return false;
} catch (Exception ex) {
transactionManager.rollback(trstatus);
ex.printStackTrace();
log.error("Error occured on Save Salary data.", ex);
return false;
}
}
You are missing return statement for the following catch block :
catch (Exception ex) {
log.error("Some error : ", ex);
}
Either you add return statement in this catch block or at the end of mehtod
If this code throws an Exception, then the following catch code will not be entered into and hence there is no return value
try {
hRMSPickSalaryDataDAO.update(regionId, circleId, yearMonth);
return true;
} catch (Exception ex) {
log.error("Some error : ", ex);
**edit**
return `true||false`;
}
} catch (...) {
return something;
}

Java exception handling get console error message

I want to get error message using java when exception are generated.
now I have java code with following scenario:
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e)
}
}
method second(){
try{
my code
}catch(Exception e){
throw new Exception("Exception generate in second method",e);
}
}
now when the first method execute then I get only "Exception generate in second method" message but there is some other message printed on console by java so how to get that console error message.
Note: I have already try with e.getMessage(); and e.printStackTrace();
Every exception has a cause that you can get with getCause(). You can go recursively down them until you get to the root cause. Here is your example with a utility that dumps the exception with all its causes like the console does.
private void first() {
try {
second();
} catch (Exception ex) {
Log.e("CATCH", getExceptionDump(ex));
}
}
private void second() {
try {
throw new UnsupportedOperationException("We don't do this.");
} catch (Exception ex) {
throw new RuntimeException("Exception in second()", ex);
}
}
private String getExceptionDump(Exception ex) {
StringBuilder result = new StringBuilder();
for (Throwable cause = ex; cause != null; cause = cause.getCause()) {
if (result.length() > 0)
result.append("Caused by: ");
result.append(cause.getClass().getName());
result.append(": ");
result.append(cause.getMessage());
result.append("\n");
for (StackTraceElement element: cause.getStackTrace()) {
result.append("\tat ");
result.append(element.getMethodName());
result.append("(");
result.append(element.getFileName());
result.append(":");
result.append(element.getLineNumber());
result.append(")\n");
}
}
return result.toString();
}
The message in the Exception constructor argument is not printed in the exception detail.
You can simply use this code to print the message :
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e.getMessage())
}
}
Hope this solves your problem
Why you cannot use print stack trace ?
Because A throwable contains a snapshot of the execution stack of its thread at the time it was created. (see Throwable)
It implies that, if you want to print the stack trace you need to use the printStackTrace() method BUT in your second method !
method second(){
try {
my code
} catch(Exception e) {
e.printStackTrace();
throw new Exception("Exception generate in second method",e);
}
}
Or using a the tricky method setStackTrace and using the printStackTrace() in first
method second(){
try {
my code
} catch(Exception e) {
Exception ex = new Exception("Exception generate in second method",e);
ex.setStackTrace(e);
throw ex;
}
}
method first(){
try {
second();
} catch(Exception e) {
e.printStackTrace();
}
}
You can print the cause of the exception you get. Try this:
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e);
if (e.getCause() != null) {
System.out.println("Cause:> " + e.getCause());
}
}
}
I believe this is the console message you want to achieve:
Error:> java.lang.Exception: Exception generate in second method
Try this code, when the catch block of the second method throws an exception the second method should declare it as throws or put a nested try catch within the catch block.
The exception is propagated to the first() method which is handled by its catch block.
public class Test {
public void first() {
try {
second();
} catch (Exception e) {
System.out.println("Error:> " + e);
}
}
public void second() throws Exception {
try {
throw new Exception();
} catch (Exception e) {
throw new Exception("Exception generate in second method", e);
}
}
public static void main(String ars[]) {
Test test = new Test();
test.first();
}
}

Categories

Resources