如何在Symfony2中包装控制器的操作?

Is it possible to wrap some controller's actions in a custom logic in Symfony2?

I would like to create an "AJAX" controller in order to handle all AJAX requests in my application. I want to remove boilerplate code from my actions to make application logic lighter. Here's some points i want to implement through wrapper:

  1. Wrap action call in a try ... catch block in order to catch all possible exceptions and transform output to a JSON one instead of general 500 HTML error pages. So I can gracefully handle them on a client side.
  2. Return plain arrays from the action calls to rewrite them later and transform them into a proper JsonResponse objects.

If it's possible to implement such a wrapper, is it also possible to enable it on a route basis?

UPDATE:

Here's my example:

/**
 * It is now.
 * @return JsonResponse
 */
public function someAction()
{
    try {

        // Some business logic here.
        $foo = getFoo();
        $bar = getBar($foo);

        // Sending response.
        return new JsonResponse([
            'success' => true,
            'data'    => [
                'foo' => $foo,
                'bar' => $bar,
            ],
        ]);

    } catch (\Exception $exception) {

        // Handle exception here. Translate error message, etc.

        return new JsonResponse([
            'success' => false,
            'message' => $exception->getMessage(),
            'code'    => $exception->getCode(),
        ]);
    }
}

/**
 * How I want it to be.
 * @return array
 */
public function someBetterAction()
{
    // Some business logic here.
    $foo = getFoo();
    $bar = getBar($foo);

    // Sending response.
    return [
        'foo' => $foo,
        'bar' => $bar,
    ];
}

In other words I just want to move exception handling and output formatting to a wrapping layer in order to make action lighter.

You could use a custom exception handler like FOSRestBundle (& Docs) which would (obviously) handle any exceptions that were created through the course of your actions.