How to Simulate 500 Error in Symfony 2

孤街醉人 提交于 2020-12-29 02:41:53

问题


I am wondering how would I simulate a 500 error in Symfony 2.

I have been reading this post where Raise suggests throwing an exception

throw new sfException('Testing the 500 error');

in Symfony 1.4.

I have been placing this code in my

\store\vendor\symfony\symfony\src\Symfony\Bundle\TwigBundle\Controller\ExceptionController.php

but I get the fatal error

Class 'Symfony\Bundle\TwigBundle\Controller\sfException' not found in /home/notroot/www/store/vendor/symfony/symfony/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php on line 49`

Line 49 refers to the exception code I added.

My question is if throwing an exception is still viable in forcing a 500 error in Symfony 2, and if so where do I put this exception?

If this is no longer viable, how would I be able to test for an error 500?


回答1:


You can do it like this.

//in your controller
$response = new Response();
$response->setStatusCode(500);
return $response;

Dont forget to add

use Symfony\Component\HttpFoundation\Response;

at the top of your file.

Edit : To force Symfony 500 error, your proposition is fine :

throw new \Exception('Something went wrong!');

Put it in a controller function.




回答2:


You can do:

throw new Symfony\Component\HttpKernel\Exception\HttpException(500, "Some description");



回答3:


The simplest way to do this is to:

return new Response('', 500);

Don't forget to include Symfony\Component\HttpFoundation\Response.




回答4:


A good way to do it can be:

use Symfony\Component\HttpKernel\Exception\HttpException;

throw new HttpException(\Symfony\Component\HttpFoundation\Response::HTTP_INTERNAL_SERVER_ERROR, 'Testing the 500 error');



回答5:


If you want to trigger a FatalErrorException in Symfony2 to see if you app is handling it correctly, you can create an action like this in your controller:

public function fatalErrorExceptionAction()
{
    $unknown->getVoid();
}

The division by zero will generate a Warning while throwing the Exception, well, it'll just throw it. :-)




回答6:


You have to use Symfony\Component\HttpKernel\Exception\HttpException.

Another way should be doing something like 1/0;, but I haven't tested it.



来源:https://stackoverflow.com/questions/14284638/how-to-simulate-500-error-in-symfony-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!