我在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致命错误:未捕获异常';异常';有消息,但这不太像我的问题,也没有简洁的答案。
请帮忙?
*编辑*
这似乎与throw
关键字有关。例如,如果我使用echo
,我会在屏幕上打印出消息,如下所示:
异常"exception",消息为"文件不存在"在C:''sites''wonderfulproject''script.php中:183堆栈跟踪:#0{main}
为什么?
**编辑2*
多亏了@Orangepill,我对如何处理异常有了更好的理解。我发现了一个很棒的芭蕾舞团,帮助很大。链接:http://net.tutsplus.com/tutorials/php/the-ins-and-outs-of-php-exceptions/
这是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)。
另一种选择是使用set_exception_handler为脚本设置默认错误处理程序。
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");
只是在这里添加一些额外的信息,以防有人和我有同样的问题。
我在代码中使用名称空间,并且我有一个类,该类具有抛出异常的函数。
然而,我在另一个类文件中的try/catch代码被完全忽略了,并且引发了未捕获异常的正常PHP错误。
结果我忘了在顶部添加"use''Exception;",添加后解决了错误。
对于
throw new Exception('test exception');
我得到了500(但在浏览器中没有看到任何东西),直到我放入
php_flag display_errors on
在我的.htaccess中(仅用于子文件夹)。还有更详细的设置,请参阅通过htaccess only 在php中启用错误显示