FriendsOfSymfony / FOSRestBundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony
http://symfony.com/doc/master/bundles/FOSRestBundle/index.html
MIT License
2.79k stars 707 forks source link

Returning errors as json #2323

Closed Segaja closed 2 years ago

Segaja commented 2 years ago

Hi, I'm using this bundle with symfony 5.3 and i was wondering how i can configure the bundle to always return json output even in error cases. Currently I get html output for errors (400, 404, 401, 403, ...) even when I run in Prod mode.

Is there some option to achieve that or do i need to write a custom exception handler?

mbabker commented 2 years ago

Set the _format key on the route config to "json" and that should do the trick.

<?php declare(strict_types=1);

namespace App\Controller\API;

use App\Entity\Event;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\Controller\Annotations\Get;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

final class EventController extends AbstractFOSRestController
{
    /**
     * @Get("/api/{version}/events/{id}", name="app_api_event_details", requirements={"id" = "\d+"}, defaults={"_format": "json"})
     */
    public function apiEventDetails(Event $event): Response
    {
        if (!$this->isGranted(Actions::VIEW, $event)) {
            throw new AccessDeniedHttpException('You are not authorized to view this event.');
        }

        return $this->handleView($this->view($event));
    }
}
Segaja commented 2 years ago

Could you be more specific which config file you mean?

Segaja commented 2 years ago

As a reminder, I'm talking about the "default symfony routes" for errors like 404, 401 and so on.

Segaja commented 2 years ago

Never mind, I solved this. I realized this is a problem of symfony itself and not this bundle. I will close this issue.

captain-igloo commented 2 years ago

I solved this by setting fos_rest.exception.serializer_error_renderer true.