Blog |

Error Monitoring In Zend 3

Error Monitoring In Zend 3
Table of Contents

Zend Framework 3 is a free and open-source PHP framework. It uses a model-view-controller (MVC) pattern which makes its structure consistent and maintainable. It also accesses the database in an object-oriented way. Instead of directly interacting with the database using SQL queries, you can use doctrine object-relational mapping (ORM) to manage the structure and relationships of your data. This makes code easier to write and maintain.

In production applications, it’s important to monitor errors so you understand your users experiences and can fix issues before more users are affected. In this tutorial, you will see how to set up Zend Framework 3 to handle errors natively and send errors to the error monitoring service Rollbar. The error message can be seen in your PHP error log or in Rollbar, including a stack trace that provides information about the line of code that caused the error.

Native error handling in Zend 3

The easiest and most basic way to handle errors is using try, catch, and finally statements. When an error is thrown in the try block, the catch block executes and handles the error. For example, you may want to record the error or present a more friendly error message to the user.

try {
  $value = 5 / 0;
}  catch (\Exception $e) {
  echo $e->getMessage();
}

In production, the application can crash due to uncaught or runtime errors, such as when an application tries to access invalid data or code or an illegal action is attempted. To avoid such situations, Zend provides a hook that lets you handle the error globally.

The Zend Framework’s onBootstrap() method can be used to attach an exception handler. This method provides two MVC events: EVENT_DISPATCH_ERROR and EVENT_RENDER_ERROR. These events are used to call a user-defined function to handle the error. Below, you can see our example named catchError() which echos the error to the console.

class Module
{
  const VERSION = '3.0.3-dev';

  public function getConfig() {
    return include __DIR__ . '/../config/module.config.php';
  }
  public function onBootstrap(MvcEvent $event)
  {
    $application = $event->getApplication();
    $config = $application->getConfig();
    $eventManager = $application->getEventManager();
    $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, [$this, catchError]);
    $eventManager->attach(MvcEvent::EVENT_RENDER_ERROR, [$this, catchError]);
  }
  public function catchError(MvcEvent $event) {
    $exception = $event->getParam('exception');
    echo "Exception: ".$exception;
  }
}

Generally, Zend errors are logged on the console. (We use echo statements to print log messages on the console.) Whenever the console is closed, these messages are lost as they cannot be stored in any permanent location. To overcome this problem, you can use logging frameworks which are responsible for storing data to any other location such as a file or a database. By default, Zend 3 does not create any log file. For logging in the Zend 3 Framework, you can use logging services like Zend log, monolog, or any other service. However, log files are still limited by the information you choose to include in your log statements. Dedicated error monitoring solutions can automatically capture additional detail.

Monitoring errors with Rollbar

Rollbar offers a real-time feed to make you aware of errors as they appear. It automatically tracks uncaught errors and crashes in your applications, providing extra contextual data to debug errors such as local variables and arguments. It groups these errors so your view is not cluttered with repeats, and you can track when an error first occurred, how many times it happened, and when it was resolved. Rollbar can also alert you to critical errors that happen following deployment, giving you better visibility into breaking changes that could affect users. We’ll show you how to send errors from Zend to Rollbar so you can track and debug them faster. To do this, we’ve created an example app which shows an application that triggers an exception when the user clicks on a button.

Screenshot of Rollbar zend 3 example

How to set up a Zend project on Rollbar

Below are some simple steps to add Zend to Rollbar. You can find more details in our Zend documentation.

Step 1: Visit https://rollbar.com and sign up for an account if you haven’t done so yet. Next, create your project and select Backend from the list of notifiers. Select the client-side access token that is generated for you. You’ll need this to configure Rollbar in the steps below.

Step 2: Open the command prompt in your project directory and type the following command:

composer require rollbar/rollbar

Step 3: As an alternative to second step, you can add "rollbar/rollbar": "^1" to your composer.json as a dependency and run the composer update.

Step 4: Configure Rollbar by adding access_token and environment config options to config/autoload/local.php and / or config/autoload/development.local.php.

return [
  // other Zend Framework 3 local autoloaded configuration
  'rollbar' => [
    'access_token' => '[insert your access token here]',
    'environment' => 'production'
  ]
];

Step 5: Add the following code to your onBootstrap() method in "module/Application/src/Module.php."

public function onBootstrap(MvcEvent $event) {
  $application = $event->getApplication();
  $config = $application->getConfig();

  Rollbar::init($config['rollbar']);

  $eventManager = $application->getEventManager();

  $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, [$this, 'onError']);
  $eventManager->attach(MvcEvent::EVENT_RENDER_ERROR, [$this, 'onError']);
}

Step 6: Last, add the onError method in the module/Application/src/Module.php.

public function onError(MvcEvent $event) {
  $exception = $event->getParam('exception');
  Rollbar::logger()->log(Level::ERROR, $exception, array(), true);
}

Test with an example Zend app

Below we have created an example application to test if it is generating an error message. You can generate an error by clicking on the "Generate uncaught exception" button.

<div class="container text-center" style="background-color:black">
  <a href="http://127.0.0.1:8080/uncaught"target="_blank">Generate Uncaught Exception</a>
</div>

When you click on the "Generate uncaught exception" button, it triggers a method of the Uncaught controller. Here, an exception is generated in the code as “E_Warning: Creating default object from empty value.”

class Uncaught extends AbstractActionController {
  public function indexAction() {
    $x = null;
    $x->foo = 5;
  }
}

Viewing errors in Rollbar

Next, open Rollbar to see what these errors look like in your account’s item page. The error we just generated should be called "E_Warning: Creating default object from empty value."

Screenshot of Rollbar zend 3 error item

You can get more information about what generated the error by clicking on the item. It then shows the full traceback including the code file, method, and line number. This helps in finding the root cause of the error.

Screenshot of Rollbar zend 3 error item details

A lot of contextual information is provided by Rollbar that will help you in troubleshooting and debugging the problems quickly. Dashboard gives you a summary of errors, showing how many times each occurred and how many people were affected. In the row of tabs, you can see that it also provides information on which people were affected, suspected deployments, and more.

Conclusion

Zend Framework 3 is an open-source, completely object-oriented, easy-to-understand framework for creating web applications. Even the best applications can have unexpected errors, which can cause the application to stop working and negatively affect the users of your app. Monitoring with Rollbar will give you better visibility into these problems so you can fix them quickly. It collects data about every error, the line number of the code, local variables, and more. It takes only a few minutes to set up, and you will have more context to track and debug problems faster in the future. You can learn more about Rollbar’s features and how they can help solve problems quickly.

If you haven’t already, sign up for a 14-day free trial of Rollbar and let us help you take control of the errors in your Zend application.

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape