Symfony2 Exception Response. Replace status code 404 with 200

I have a 404 handler in symfony2, which is an EventListener.

With certain 404 years, I am doing a redirection that works great. No 404 selected for browser.

new RedirectResponse( $newURL ); 

This line basically replaces the 404 status code with 200.

In other cases, however, I want to return some content instead, not a 404 message, but some replacement data. Something like that:

 $response = new Response( $returnJSONMessage ); $response->headers->set( 'Content-Type', 'application/json' ); $response->setStatusCode(200); 

The code is wise, that's fine, but it does not stop returning 404. I guess because it sits inside this:

 $event->setResponse( $theResponse ); 

What type of GetResponseForExceptionEvent.

What I need for the call is to make it return my data as 200 instead of 404. Just like RedirectResponse seems. I tried:

 $event->stopPropagation(); 

But this is a little after the fact. It seems that everything in $ event-> setResponse, which is not a RedirectResponse, gets in this case a value of 404.

Any ideas?

+4
source share
2 answers

Finally, I found what I was looking for using Symfony GitHub pull;

 $response->headers->set( 'X-Status-Code', 200 ); 

Allows you to override the exception status code.

 $response->setStatusCode(200); 

Does not work.

Request here: https://github.com/symfony/symfony/pull/5043

Pull here: https://github.com/symfony/symfony/commit/118a5d2274dc7d6701c3e2a758b820cd49ebaf3b

+13
source

I solved this problem after the code.

 use Symfony\Component\HttpKernel\Exception\HttpException; ... $event->setException(new HttpException(200)); 
+1
source

Source: https://habr.com/ru/post/1498445/


All Articles