Skip to content
Advertisement

How to throw a 400 bad request from a symfony controller?

I have set up a very simple stub of a Symfony 3.3 controller whose main action looks looks like this:

/**
 * @Route("/pair-gallery/{id}")
 */
public function indexAction(Int $id)
{
    $output = [];
    return new JsonResponse($output);
}

When I give it a string as an argument in the url (rather than an integer), I currently get a 500 error. That’s not horrible, but it’s not exactly what I want.

How do I tell Symfony to send back a 400 (“Bad Request”) response code instead?

Advertisement

Answer

You can simply throw a exception that get automatically transformed to a HTTP 400 response:

throw new BadRequestHttpException('Message');

If you want to be specific about the thrown http error code (maybe you want to throw an obscure error code like 418) you can pass it as the third parameter:

throw new BadRequestHttpException('Message', null, 418);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement