3

I'm working on a JSON API right now using FOSRestBundle. I'm having some trouble dealing with errors outside my API's routing spacing because Symfony seems hell-bent on requiring Twig in order to capture HttpException, and I obviously have no use for twig other than on the dev controller (for the web debug tools).

The end result is that I'm getting 500 errors when I try to access any resources not being handled by routing, instead of a 404, when using the prod controller. This is unsightly. Proper http codes are given back when using the dev controller, as Twig is active on it.

How can I tap into symfony to handle errors my way without requiring Twig enabled on production, short of catching exceptions on the prod controller?

1

1 Answer 1

1

Yes! If I understand your use-case correctly, you can create a custom exception controller:

  1. Redefine the twig.controller.exception.class parameter
  2. Create a custom controller

Here's an example from one of my projects:

In app/config/services.yml or wherever is appropriate for your project, add:

parameters:
    twig.controller.exception.class: AppBundle\Controller\ExceptionController

Then create custom controller src/AppBundle/Controller/ExceptionController.php:

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;

/**
 * ExceptionController
 *
 * Override standard exceptions
 * in production env with basic
 * json response codes.
 *
 * @see app/config/services.yml
 */
class ExceptionController extends BaseExceptionController
{
    /**
     * {@inheritdoc}
     */
    public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
    {
        if ($request->attributes->get('showException', $this->debug)) {
            return parent::showAction($request, $exception, $logger);
        }

        return new JsonResponse(null, $exception->getStatusCode());
    }
}

In my project this returns {} with the appropriate HTTP response code in prod. Obviously your use-case might require different logic, which you can implement easily enough in your custom ExceptionController::showAction() method.

Hope this helps :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.