PHP:触发致命错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15887070/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:08:04  来源:igfitidea点击:

PHP: Trigger fatal error?

phpfatal-error

提问by DudeOnRock

I would like to be able to throw a fatal, uncatchable error in my php class when a user of my class abuses it for something I did not intend. I don't want him/her to be able to recover with a catch clause. I know about trigger_error, but I can only make it issue warnings or notices.

我希望能够在我的 php 类中抛出一个致命的、无法捕捉的错误,当我的类的用户为了我不想要的东西滥用它时。我不希望他/她能够通过 catch 条款恢复。我知道trigger_error,但我只能让它发出警告或通知。

回答by bwoebi

E_USER_ERROR is the suited constant.

E_USER_ERROR 是适合的常量。

trigger_error("Fatal error", E_USER_ERROR);

See also the first example of the manual pageand the list of PHP Errors(only ones beginning with E_USER* may be issued from trigger_error).

另请参阅手册页的第一个示例和PHP 错误列表(只有以 E_USER* 开头的错误可能会从 trigger_error 发出)。

回答by Brad Kent

Note: if you're using a custom error handler (see set_error_handler) E_USER_ERRORwill NOT halt/exit/die unless the error handler returns false

注意:如果您使用自定义错误处理程序(请参阅set_error_handler), E_USER_ERROR除非错误处理程序返回 false,否则不会停止/退出/死亡

nutshell : your custom error handler effectively determines if E_USER_ERRORis treated as a fatal

简而言之:您的自定义错误处理程序有效地确定是否E_USER_ERROR被视为致命错误

回答by Why 50 points to comment...

debug_print_backtrace();
trigger_error("As much information as you can provide, please", E_USER_ERROR);
exit();

exit() terminates the PHP script entirely. The more information you can provide users or developers about the error, the better. Error codes are passé.

exit() 完全终止 PHP 脚本。您可以向用户或开发人员提供有关错误的信息越多越好。错误代码已经过时。

Edit: use of E_USER_ERROR should terminate the script anyway, so moved debug_print_backtrace() before trigger_error().

编辑:无论如何使用 E_USER_ERROR 应该终止脚本,所以在 trigger_error() 之前移动了 debug_print_backtrace()。

回答by AliN11

If you are using PHP 7 or higher, Errorclass works too:

如果您使用的是 PHP 7 或更高版本,Error类也可以使用:

$flag = false;

try {
    if ($flag == false) {
        throw new Error('An error occured');
    }
} catch (Error $e) {
    echo $e->getMessage();
}

If you put throw new Error('An error occured');outside the Try Catch, You will get a Fatal Error.

如果你把它放在throw new Error('An error occured');外面Try Catch,你会得到一个致命错误。