PHP 错误处理:die() Vs trigger_error() Vs throw Exception
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7063053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Error handling: die() Vs trigger_error() Vs throw Exception
提问by CuriousMind
In regards to Error handling in PHP -- As far I know there are 3 styles:
关于 PHP 中的错误处理——据我所知有 3 种样式:
die()
orexit()
style:$con = mysql_connect("localhost","root","password"); if (!$con) { die('Could not connect: ' . mysql_error()); }
throw Exception
style:if (!function_exists('curl_init')) { throw new Exception('need the CURL PHP extension. Recomplie PHP with curl'); }
trigger_error()
style:if(!is_array($config) && isset($config)) { trigger_error('Error: config is not an array or is not set', E_USER_ERROR); }
die()
或exit()
风格:$con = mysql_connect("localhost","root","password"); if (!$con) { die('Could not connect: ' . mysql_error()); }
throw Exception
风格:if (!function_exists('curl_init')) { throw new Exception('need the CURL PHP extension. Recomplie PHP with curl'); }
trigger_error()
风格:if(!is_array($config) && isset($config)) { trigger_error('Error: config is not an array or is not set', E_USER_ERROR); }
Now, in the PHP manual all three methods are used.
现在,在 PHP 手册中使用了所有三种方法。
What I want to know is which style should I prefer & why?
Are these 3 drop in replacements of each other & therefore can be used interchangeably?
我想知道的是我应该更喜欢哪种风格以及为什么?
这 3 种是否可以相互替代并因此可以互换使用?
Slightly OT: Is it just me or everyone thinks PHP error handling options are just too manyto the extent it confuses php developers?
有点 OT:是我还是每个人都认为 PHP 错误处理选项太多以至于让 php 开发人员感到困惑?
采纳答案by Linus Kleen
The first one should never be used in production code, since it's transporting information irrelevant to end-users (a user can't do anything about "Cannot connect to database").
第一个永远不应该在生产代码中使用,因为它传输与最终用户无关的信息(用户不能对“无法连接到数据库”做任何事情)。
You throw Exceptions if you know that at a certain critical code point, your application can failand you want your code to recover across multiple call-levels.
如果您知道在某个关键代码点,您的应用程序可能会失败,并且您希望您的代码在多个调用级别之间恢复,那么您就会抛出异常。
trigger_error()
lets you fine-grain error reporting (by using different levels of error messages) and you can hide those errors from end-users (using set_error_handler()
) but still have them be displayed to you during testing.
trigger_error()
允许您细粒度的错误报告(通过使用不同级别的错误消息),您可以对最终用户隐藏这些错误(使用set_error_handler()
),但在测试期间仍会向您显示它们。
Also trigger_error()
can produce non-fatal messages important during development that can be suppressed in production code using a custom error handler. You can produce fatal errors, too (E_USER_ERROR
) but those aren't recoverable. If you trigger one of those, program execution stopsat that point. This is why, for fatal errors, Exceptions should be used. This way, you'll have more control over your program's flow:
还trigger_error()
可以生成在开发过程中重要的非致命消息,可以使用自定义错误处理程序在生产代码中抑制这些消息。您也可能产生致命错误 ( E_USER_ERROR
) 但这些错误是不可恢复的。如果您触发其中之一,程序执行将在该点停止。这就是为什么,对于致命错误,应该使用异常。这样,您就可以更好地控制程序的流程:
// Example (pseudo-code for db queries):
$db->query('START TRANSACTION');
try {
while ($row = gather_data()) {
$db->query('INSERT INTO `table` (`foo`,`bar`) VALUES(?,?)', ...);
}
$db->query('COMMIT');
} catch(Exception $e) {
$db->query('ROLLBACK');
}
Here, if gather_data()
just plain croaked (using E_USER_ERROR
or die()
) there's a chance, previous INSERT
statements would have made it into your database, even if not desired and you'd have no control over what's to happen next.
在这里,如果gather_data()
只是简单地(使用E_USER_ERROR
或die()
)有机会,先前的INSERT
语句就会将其放入您的数据库中,即使不需要并且您无法控制接下来会发生什么。
回答by Emil Vikstr?m
I usually use the first way for simple debugging in development code. It is not recommended for production. The best way is to throw an exception, which you can catch in other parts of the program and do some error handling on.
我通常使用第一种方式在开发代码中进行简单的调试。不建议用于生产。最好的方法是抛出一个异常,你可以在程序的其他部分捕获它并对其进行一些错误处理。
The three styles are not drop-in replacements for each other. The first one is not an error at all, but just a way to stop the script and output some debugging info for you to manually parse. The second one is not an error per se, but will be converted into an error if you don't catch it. The last one is triggering a real error in the PHP engine which will be handled according to the configuration of your PHP environment (in some cases shown to the user, in other cases just logged to a file or not saved at all).
这三种风格不是相互替代的。第一个根本不是错误,而只是一种停止脚本并输出一些调试信息供您手动解析的方法。第二个本身不是错误,但如果你不抓住它就会转换成错误。最后一个是在 PHP 引擎中触发一个真正的错误,它将根据您的 PHP 环境的配置进行处理(在某些情况下向用户显示,在其他情况下只是登录到文件或根本不保存)。