How to set up a default operation whenever a catch block get executed?

Zartof :

For debugging purposes i want my Java application to upload a log file on my MySql database whenever a catch clause is executed, regardless of which exception is thrown.

The worst solution i thought to was to add my uploader method into each catch in my code (as I already did for the creation of my log file) . This is obviously not elegant method, as long it's repeated code. So my question is: it exist someway (maybe in project proprieties) to set a default operation to be executed whenever a catch clause is met?

ItFreak :

One option would be to use a logging framework (no matter if you write this your self or use an existing solution), so you can do:

try{}
catch(Exception e) {Logger.logExceptionToDatabase(e); }

In this you could handle the upload into your database. However I do not thinkt that it is very useful to upload error logs into your database each time a catch block gets executed. I would write them to seperate text logs and collect them and only persist them to a database from time to time or by user request.

To the question itself: This is not possible, however there is a finally block which gets executed after the according try block (as long as the JVM is not terminated within the try block). Maybe you could introduce some TransactionResult and do a logging for each success and failure and than do:

TransactionResult transactionResult;

try{
//do work and at the last line in the try after each operation that could 
have failed has been executed set your transactionResult variable
transactionResult = new SuccessTransaction();
}
catch(Excpetion e) { transactionResult=  new FailureTransaction();}
finally {Logger.logTransaction(transactionResult); }

and the according classes:

public interface TransactionResult{
  public void writeLog();

} 

and an example of an transaction result:

public class SuccessTransaction implements TransactionResult{
private String resultStatus;

public SuccessTransaction() { this.resultStatus = "success"; }

public void writeLog() { System.out.println(this.resultStatus); } //or whatever you want to do with your result

}

same goes for your failure instance.

Update

As you stated that there are many Exceptions, you could also pass your Exception to your concrete FailureTransaction and than simply write that message out or collect all the failures in a list and then you can trace which exceptions have been triggered.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88831&siteId=1