Trigger Error 404.json.twig

I am trying to return a customized json error pattern that will be returned by Symfony, but it will continue to return an HTML version. Using the client for the rest, I set Accept and Content-Type to "application / json", but only the contents of my error404.html.twig are returned, not error404. The json.twig file.

I am currently testing this with a completely invalid URL (i.e. no route), but as soon as I have this work, I will also use it for valid URLs that do not result in a resource, and inside the code is HttpNotFoundException

+4
source share
1 answer

Setting the headers in your request will not actually affect which error pattern will be returned, even though it looks like a logical path. The generated error template is based on the request format, which is either set in the parameter _formator manually in the object itself Request. There is a solution in this message , but if you get a 404 error, you cannot set the parameter exactly _formator $request->setRequestFormat('json')from the Controller that did not exist.

Symfony , , , , , ExceptionController. , showAction() findTemplate(), Accept application/json. Content-Type . , :

# app/config/services.yml
services:
    app.exception_controller:
    class: AppBundle\Controller\CustomExceptionController
    arguments: ['@twig', '%kernel.debug%']

Twig:

# app/config/config.yml
twig:
    exception_controller:  app.exception_controller:showAction

, . showAction(), Accept Request:

namespace AppBundle\Controller;

use Symfony\Bundle\TwigBundle\Controller\ExceptionController;

class CustomExceptionController extends ExceptionController
{
    /*
     * {@inheritDoc}
     */
    public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
    {
        if (in_array('application/json', $request->getAcceptableContentTypes())) {
            $request->setRequestFormat('json');
        }

        parent::showAction($request, $exception, $logger);
    }
}

Symfony , findTemplate() - , , . Content-Type , :

namespace AppBundle\Controller;

use Symfony\Bundle\TwigBundle\Controller\ExceptionController;

class CustomExceptionController extends ExceptionController
{
    /*
     * {@inheritDoc}
     */
    protected function findTemplate(Request $request, $format, $code, $showException)
    {
        if (in_array('application/json', $request->getAcceptableContentTypes()) &&
            0 === strpos($request->headers->get('Content-Type'), 'application/json')
        ) {
            $format = 'json';
        }

        parent::findTemplate($request, $format, $code, $showException);
    }
}

, kernel.exception .

FOSRestBundle, , Request Accept . , .

+4

Source: https://habr.com/ru/post/1626100/


All Articles