Fix the $app that is not initialize in case of errors

Some error may generate a fatal PHP error due to the fact that the $app is not initialized.

So we replaced the $app that is not initialized by its normal value JFactory::getApplication() to avoid initializing the $app when this is not required.