I have a 404 handler in symfony2 which is an EventListener.
With certain 404's, I do a redirect, which works great. To the browser, no 404 is thrown.
new RedirectResponse( $newURL );
That line basically replaces the 404 status code with a 200.
In other cases though, I want to return some content instead, not a 404 message, but some replacement data. Something like this:
$response = new Response( $returnJSONMessage );
$response->headers->set( 'Content-Type', 'application/json' );
$response->setStatusCode(200);
Code wise, this is fine, but it doesn't stop the 404 being returned. I am guessing because it sits within this:
$event->setResponse( $theResponse );
Which is of type GetResponseForExceptionEvent.
What do I need to call, to get it to return my data as a 200 instead of a 404. In the same way that RedirectResponse seems to. I tried:
$event->stopPropagation();
But it is a bit after the fact. It seems anything within $event->setResponse which isn't a RedirectResponse gets labelled a 404 in this case.
Any ideas?
Finally found what I was looking for via a Symfony GitHub pull;
$response->headers->set( 'X-Status-Code', 200 );
Allows you to override the exception status code.
$response->setStatusCode(200);
Will not work.
Request here: https://github.com/symfony/symfony/pull/5043
Pull here: https://github.com/symfony/symfony/commit/118a5d2274dc7d6701c3e2a758b820cd49ebaf3b
I resolved this issue following code.
use Symfony\Component\HttpKernel\Exception\HttpException;
...
$event->setException(new HttpException(200));
The suggestions provided here didn't work for me.
And then I found out why - X-Status-Code is deprecated since Symfony 3.3.
What worked for me was using $event->allowCustomResponseCode();
$exception = $event->getException();
$response = new Response('...', 404);
// ...
$event->allowCustomResponseCode();
$event->setResponse($response);
Here is a link about this on Symfony website
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