Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Exception Response. Replace 404 status code with 200

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?

like image 713
Adi Avatar asked Aug 22 '13 17:08

Adi


3 Answers

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

like image 92
Adi Avatar answered Sep 26 '22 19:09

Adi


I resolved this issue following code.

use Symfony\Component\HttpKernel\Exception\HttpException;
...
$event->setException(new HttpException(200));
like image 37
Koichi Higashi Avatar answered Sep 24 '22 19:09

Koichi Higashi


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

like image 30
Zavra Avatar answered Sep 22 '22 19:09

Zavra