Change HTML errors to JSON #42441
-
Hi guys! A quick question: class LanguagesDictionaryController extends AbstractController
{
#[Route('/api/dictionaries/language', name: 'dictionaries/get_languages', methods: 'GET', )]
public function getLanguagesDictionary(): JsonResponse
{
return $this->json('...some data');
}
} But whenever for example I try to POST, PUT, or else the error is in HTML format instead of JSON? How could I possibly archive that? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
You need to install serializer in order for Symfony's json error handler to kick in. Other alternative would be to create an exception handler which would set response to json. As an example. class JSONExceptionListener implements EventSubscriberInterface
{
/**
* @var string
*/
private $environment;
public function __construct(string $environment)
{
$this->environment = $environment;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => ['onKernelException', 200],
];
}
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
$content = [
'code' => $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500,
'message' => $exception->getMessage(),
'trace' => \in_array($this->environment, ['dev', 'test'], true)
? $exception->getTrace()
: [],
];
$event->setResponse(
new JsonResponse($content, $content['code'])
);
}
} |
Beta Was this translation helpful? Give feedback.
-
@alexanderkatkov if any of the provided answers solved your issue, please click on their "Mark as answer" icon. Thanks! |
Beta Was this translation helpful? Give feedback.
You need to install serializer in order for Symfony's json error handler to kick in.
See https://symfony.com/doc/current/controller/error_pages.html#overriding-error-output-for-non-html-formats
Other alternative would be to create an exception handler which would set response to json.
As an example.