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 . , :
services:
app.exception_controller:
class: AppBundle\Controller\CustomExceptionController
arguments: ['@twig', '%kernel.debug%']
Twig:
twig:
exception_controller: app.exception_controller:showAction
, . showAction(), Accept Request:
namespace AppBundle\Controller;
use Symfony\Bundle\TwigBundle\Controller\ExceptionController;
class CustomExceptionController extends ExceptionController
{
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
{
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 . , .