This a good solution to prevent the log object from being rollbacked. Please note, however, that when a exception would occur in the creation of the log object, no rollback mechanism is used now. To facilitate this, the startTransaction()
, endTransaction()
and rollbackTransaction()
methods of IContext can be used.
The method startTransaction()
starts a new transaction, or when the context is already in a transaction, creates a savepoint.
The endTransaction()
method commits the current transaction if no savepoints are present, otherwise a savepoint is removed.
Finally, rollbackTransaction()
rolls back the entire current transaction if no savepoints are present, otherwise a rollback to the last savepoint is performed.
In your example, this can be applied as follows:
public void writeLog(String logMessage, Exception e, boolean throwUserException, String logNodeName) throws CoreException, UserException
{
String fullErrorString = logMessage + ": " + e.toString() + ": " + e.getMessage();
Core.getLogNode(logNodeName).error(fullErrorString);
IContext newContext = new Context((Session)this.context.getSession());
newContext.startTransaction();
try
{
Log log = Log.create(newContext);
log.setLogMessage(fullErrorString);
log.setLog_Account(currentAccount);
Core.commit(newContext, log.getMendixObject());
}
catch(CoreException e)
{
newContext.rollbackTransaction();
throw new MendixRuntimeException(e);
}
newContext.commitTransaction();
if (throwUserException)
{
throw new UserException(ExceptionCategory.Custom, fullErrorString);
}
}
Looks like I found out. I'm using a new Context to commit the Log object. New writeLog method:
public void writeLog(String logMessage, Exception e, boolean throwUserException, String logNodeName) throws CoreException, UserException
{
String fullErrorString = logMessage + ": " + e.toString() + ": " + e.getMessage();
Core.getLogNode(logNodeName).error(fullErrorString);
IContext newContext = new Context((Session)this.context.getSession());
Log log = Log.create(newContext);
log.setLogMessage(fullErrorString);
log.setLog_Account(currentAccount);
Core.commit(newContext, log.getMendixObject());
if (throwUserException)
{
throw new UserException(ExceptionCategory.Custom, fullErrorString);
}
}