11

我正在玩 PHP 中的异常。例如,我有一个读取 $_GET 请求并加载文件的脚本;如果文件不存在,应该抛出一个新的异常:

if ( file_exists( $_SERVER['DOCUMENT_ROOT'] .'/'.$_GET['image'] ) ) {
    // Something real amazing happens here.
}
else {
    throw new Exception("The requested file does not exists.");
}

问题是,当我尝试为测试提供一个不存在的文件时,我得到一个 500 错误而不是异常消息。服务器日志如下:

[09-Jul-2013 18:26:16 UTC] PHP Fatal error:  Uncaught exception 'Exception' with message 'The requested file does not exists.' in C:\sites\wonderfulproject\script.php:40
Stack trace:
#0 {main}
  thrown in C:\sites\wonderfulproject\script.php on line 40

我想知道我是否在这里遗漏了一些非常明显的东西。

我已经检查了这个问题PHP fatal error: Uncaught exception 'Exception' with message但它不太像我的问题,并且没有简明的答案。

请帮忙?

* 编辑 *

这似乎与throw关键字有关。echo例如,如果我使用,我会在屏幕上打印消息,如下所示:

带有消息“文件不存在”的异常“异常”。在 C:\sites\wonderfulproject\script.php:183 堆栈跟踪:#0 {main}

这是为什么?

** 编辑 2 **

感谢@Orangepill,我对如何处理异常有了更好的理解。我从 nettuts 那里找到了一个很棒的 tut,它很有帮助。链接: http: //net.tutsplus.com/tutorials/php/the-ins-and-outs-of-php-exceptions/

4

3 回答 3

22

这是 display_errors 关闭的未捕获异常的预期行为。

您在此处的选项是通过 php 或在 ini 文件中打开 display_errors 或捕获并输出异常。

 ini_set("display_errors", 1);

或者

 try{
     // code that may throw an exception
 } catch(Exception $e){
     echo $e->getMessage();
 }

如果你抛出异常,其目的是在更远的地方有东西会捕获并处理它。如果不是,则为服务器错误 (500)。

Another option for you would be to use set_exception_handler to set a default error handler for your script.

 function default_exception_handler(Exception $e){
          // show something to the user letting them know we fell down
          echo "<h2>Something Bad Happened</h2>";
          echo "<p>We fill find the person responsible and have them shot</p>";
          // do some logging for the exception and call the kill_programmer function.
 }
 set_exception_handler("default_exception_handler");
于 2013-07-09T18:54:03.260 回答
9

Just adding a bit of extra information here in case someone has the same issue as me.

I use namespaces in my code and I had a class with a function that throws an Exception.

However my try/catch code in another class file was completely ignored and the normal PHP error for an uncatched exception was thrown.

Turned out I forgot to add "use \Exception;" at the top, adding that solved the error.

于 2014-04-14T22:01:50.610 回答
0

For

throw new Exception('test exception');

I got 500 (but didn't see anything in the browser), until I put

php_flag display_errors on

in my .htaccess (just for a subfolder). There are also more detailed settings, see Enabling error display in php via htaccess only

于 2017-10-05T01:08:02.953 回答