Blog |

Error Monitoring in Symfony

Error Monitoring in Symfony
Table of Contents

Symfony is a PHP model-view-controller framework used to develop web applications. The main reasons Symfony has acclaimed fame among the developer community are its database engine compatibility, its faster development and its robust system. These features make it easy to develop and customize web applications.

To make your web application successful, you should consider how user experience is affected by the inevitable errors that pop up in production. Customers can walk away from a purchase or churn out from a subscription when applications do not run properly. A fast response to critical problems is essential. To minimize customer impact, it is important to track and fix issues quickly.

In this tutorial, we’ll show you how to add native error handling so you can capture handled and unhandled errors. Doing so lets you present a clear message to the user as well as track the error to prioritize fixes.

Then, we’ll show you how to monitor errors using Rollbar. Rollbar is an error monitoring service that tracks errors centrally and gives you tools to better monitor and troubleshoot problems in production. We'll show a working example for Symfony 3, but Rollbar also supports Symfony 4.

Rollbar and Symfony

Native error handling in Symfony 3

Starting at the most basic level, error handling can be achieved using try, catch and finally statements. These statements can be used to handle caught exceptions in Symfony components.

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

Symfony 3 also offers multiple approaches to handling uncaught exceptions. Below is one example by which you can handle an uncaught exception globally and report it to error reporting services like Rollbar. Below are some simple steps to create a global error handler in Symfony 3:

Step 1:

Find the AppBundle in your project and create a package for a global error handler. In our case it is EventListener. You can find AppBundle under the src folder in the project directory.

Step 2:

Next, create a global error handler in the EventListener package. You can handle errors here using a function named onKernelException.

<?php
// src/AppBundle/EventListener/ExceptionListener.php
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionListener
{
  public function onKernelException(GetResponseForExceptionEvent $event)
  {
    // You get the exception object from the received event
    $exception = $event->getException(); // Catch your exception here.
    // Customize your response object to display the exception details
    $response = new Response();
    $response->setContent($exception);        
    // sends the modified response object to the event
    $event->setResponse($response);
  }
}

Step 3:

Finally, register the global error handler in the service.yml file. You can find it under the config directory of your root project.

AppBundle\EventListener\ExceptionListener:
  tags:
    - { name: kernel.event_listener, event: kernel.exception }

This is a great way to present a better formatted error page to the user. However, you should have a way to track how often these errors happen and a method of receiving alerts about potentially critical user experience issues. Also, you need sufficient contextual information to determine the cause of the problem so you can fix it quickly. It’s better to capture this data automatically so you don’t have to rely on complaints to your support team.

Monitoring errors with Rollbar

Rollbar helps you monitor real world applications, providing live error feed and instant alerts to make you aware of errors as they appear. It automatically tracks errors and provides contextual data to debug errors. No error reports or feedback from the user are required to identify these errors. Rollbar can quickly track and resolve errors. It offers information related to errors using statistics, charts and historical graphs. Learn more about Rollbar’s features and how they can help solve problems quickly.

Below, we've created an example symfony app that triggers an exception when the user clicks on a button. The error message is recorded on Rollbar with a stack trace where you can see the line of code that caused the error.

Screenshot of Rollbar Symfony Example

How to set up a Symfony project on Rollbar

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

  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.

  2. Open the command prompt in your project directory and type the following command to install the Rollbar Symfony SDK:

composer require rollbar/rollbar-php-symfony3-bundle
  1. Register Rollbar\Symfony\RollbarBundle\RollbarBundle in AppKernel::registerBundles()
public function registerBundles()
{
    $bundles = [
        // ...
        new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
        // ...
        new Symfony\Bundle\MonologBundle\MonologBundle(),
        // ...
        new Rollbar\Symfony\RollbarBundle\RollbarBundle(),
        // ...
    ];

    return $bundles;
}
  1. Configure Rollbar in your app/config.yml or app/config_*.yml.
rollbar:
  access_token: YourAccessToken
  environment: YourEnvironmentName

monolog:
  handlers:
    rollbar:
      type: service
      id: Rollbar\Monolog\Handler\RollbarHandler
  1. As an alternative to step 4, to configure Rollbar in your Symfony app, you can add the code below in the AppBundle\Controller class. Normally you can find Controller class under the \vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Controller folder of your project root directory.
use \Rollbar\Rollbar;
use \Rollbar\Payload\Level;
Rollbar::init(
  array(
    'access_token' => YourAccessToken
    'environment' => YourEnvironmentName
  )
);

Test Rollbar with an example Symfony app

We've created a page to test if it is generating an error message. In the example below, you can generate an error by clicking the "Generate an error" button.

<html>
  <body>
    <div class="col-sm-15 mainContainer ">
      <h3><i>Rollbar Symfony3 Example</i></h3>
      <br><br>
        <a href="{{ path('error') }}" >
        <input type="submit" value="Generate Caught Error" class="btn btn-primary">
        </a>          
    </div>
  </body>
</html>

When you click the "Generate an error" button it triggers the uncaught method of DefaultController where we are generating a “Creating default object from empty value: Creating default object from empty value” exception.

class DefaultController extends Controller
{
  /**
    * @Route("/uncaught", name="uncaught")
    */
  public function uncaught(Request $request)
  {
        $x = null;
        $x->foo = 5; // Null field access
  }
  /**
    * @Route("/", name="homepage")
    */
  public function show(Request $request)
  {
      // replace this example code with whatever you need
        return $this->render('demo/base.html.twig');
  }
}

Viewing errors in Rollbar

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

Screenshot of Rollbar symfony error item

You can get more information about what generated the error by clicking on the item where you can see a traceback showing the exact source code file, method and line number. This provides more context to help you find the root cause of errors.

Screenshot of Rollbar symfony error detail

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.

Conclusion

Symfony is a powerful and robust PHP framework. It has unique ways of handling errors. Error monitoring is one of the most important tools for identifying and fixing errors. Rollbar helps you monitor the errors, prioritize high-impact ones, and capture more contextual data so you can fix problems faster. It provides developers with information about what happened before, during and after an error was generated.

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

"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