As @DmitryRekun said, a good discussion is here. The key piece to consider in all of this is what type of error do you have?
There are two types of errors:
- Recoverable
- Unrecoverable.
The difference I tend to sum up as follows:
Can I still show the page that was requested, even though this error occurred?
- Yes? - Recoverable
- No? - Unrecoverable
Now that we know what we are dealing with. What should you do?
If the error is unrecoverable, you want to redirect them to an error page instead of continuing on to the requested page. That is as simple as the following:
throw new Exception(JText::_('COM_MYCOMP_ERROR_MESSAGE_NOT_FOUND'), 404);
Exception
is a class that takes two parameters, a message and a code. It is recommended to try to use the HTTP Response Codes if they fit your scenario.
If the error is recoverable, you likely just want to display a message back to the end user while still showing them the page that they requested. This typically means that you should 'enqueue' a message for the application:
JFactory::getApplication()->enqueueMessage($error, 'error');
enqueueMessage
takes two parameters, the error message and a message type. More info here (at the bottom).
There is also a third situation that occurs fairly often for me at least. Joomla will throw exceptions for different errors (such as a database query error). This means that Joomla thinks that this error is unrecoverable. However, you may want to continue on anyway. (For example, if I'm altering a table on update of my extension, I can just run the ALTER
query, which will throw an exception if the table has previously been altered.)
In that case, you want to wrap the code that might throw an exception in a try...catch section:
try {
// exception generating code
throw new Exception('Normally you would have other code that calls a class that throws the exception', 500);
} catch (Exception $e) {
$msg = $e->getMessage(); // Returns "Normally you would have other code...
$code = $e->getCode(); // Returns '500';
JFactory::getApplication()->enqueueMessage($msg, 'error'); // commonly to still display that error
}
Note that what you are doing is "catching" the unrecoverable error and forcing the system to recover and continue showing the requested page.
Add all this up and your case should be an unrecoverable error. (I know this because you have 'return false' afterwards, so you likely don't plan to continue and are giving up on the function.)
Thus I would rewrite this as follows:
// Check for errors.
if (count($errors = $this->get('Errors')))
{
throw new Exception(implode("\n", $errors), 500);
return false; // you can remove this too, technically since the exception will take you out of this function.
}