9/16/2019 - 8:47 AM

Joomla PHP Error Handling

Joomla PHP Error Handling



There are two types of errors:

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.


Here is how I'm managing an errors.

View or Controller

    $this->item = $this->get('Item');
catch (Exception $e)
    if ($e->getCode() == 404)
        // Not found
        throw new Exception($e->getMessage(), 404);

    // Generic errors
    JFactory::getApplication()->enqueueMessage(JText::_('COM_MYCOMP_ERROR_OCCURRED'), 'error');
So if I get a 404 code from my Model (for example):

if (empty($data))
    throw new Exception(JText::_('COM_MYCOMP_ERROR_MESSAGE_NOT_FOUND'), 404);
Then I catch it in the view or controller and throw one more Exception that Joomla will handle and will display 404 page. For any other I just show some generic error message to the user.