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?
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);
For those who got here solving same issue, but for Symfony 5
$response = new JsonResponse($output, 400);
return $response->send(); // Send it !
Symfony Docs
you can specify the return code like this:
return new JsonResponse($output, 400);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With