cancel
Showing results for 
Search instead for 
Did you mean: 

try/catch in javascript

marutiprasad
Champ in-the-making
Champ in-the-making
Hi,

I am using an action to execute a java script which extracts/import a zip to a location xyz. If the zip is corrupted i need to log the same in a log file.In the positive case it is working properly. But in the negative scenatio (if the zip is corrupted) the logging code is not working.

here is my code
var tempnodepath = "repository/temps";
var lognodepath = "repository/LOGS";
var lognode = companyhome.childByNamePath(lognodepath);
var tempnode = companyhome.childByNamePath(tempnodepath);
var errorlog = lognode.childByNamePath("error_log.txt");
if(errorlog == null || errorlog.length = 0){
   errorlog = lognode.createFile("error_log.txt");
}
// take the filename only, remove the extension
var tempfilename = document.properties.name.substring(0,document.properties.name.lastIndexOf("."));
// create the folder
var tempfolder = tempnode.createFolder(tempfilename);
// import the zip into the newly created "temp"
var extractor = actions.create("import");
extractor.parameters.destination = tempfolder.nodeRef;
extractor.parameters.encoding = "utf-8";
try{   
   extractor.execute(document);
   }catch(exception){
   errorlog.content = exception.message + "\r\n";
}

ps: I have configured a rule to execute the above script when a zip is added to the folder called uploads.
6 REPLIES 6

mikeh
Star Contributor
Star Contributor
The execute() exception probably marks the whole transaction for rollback, so your error content never gets committed to the repository.

It's better to return an error HTTP response or, if that's not practical, at least raise an error in the logs.

Thanks,
Mike

marutiprasad
Champ in-the-making
Champ in-the-making
Hi Mike,

agreed your suggestion, but what if i want to update a log file, like a simple text file which is there is company home/logs. I can't update the same right?

mikeh
Star Contributor
Star Contributor
The update would also be rolled back, yes.

Mike

gordon_liang
Champ on-the-rise
Champ on-the-rise
If I really want to catch an error in javascript and ignore it, is it feasible? I tried using the try/catch statement, but seems that it does not work. The script still exist with error so the content got "roll back".

rjohnson
Star Contributor
Star Contributor
I have tried & never managed it.

mrogers
Star Contributor
Star Contributor
There may be one or two situations when you can catch an exception in alfresco java script and ignore the error.   However that is very much an edge case and could be considered a bug.    

The rule when using the alfresco or Java API is that exceptions are fatal to the transaction.   You may decorate the exception, by throwing another exception but you can't "ignore" one, your transaction is rolling back.