Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

symfony

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?

like image 235
Patrick Avatar asked Mar 13 '18 09:03

Patrick


3 Answers

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);
like image 177
FMK Avatar answered Nov 03 '22 17:11

FMK


For those who got here solving same issue, but for Symfony 5

$response = new JsonResponse($output, 400);  

return $response->send(); // Send it !

Symfony Docs

like image 41
Nedvajz Avatar answered Nov 03 '22 16:11

Nedvajz


you can specify the return code like this:

return new JsonResponse($output, 400);
like image 9
Alessandro Minoccheri Avatar answered Nov 03 '22 15:11

Alessandro Minoccheri