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.
5 Answers
E_USER_ERROR is the suited constant.
trigger_error("Fatal error", E_USER_ERROR);
See also the first example of the manual page and the list of PHP Errors (only ones beginning with E_USER* may be issued from trigger_error).
1 Comment
Note: if you're using a custom error handler (see set_error_handler)
E_USER_ERROR will NOT halt/exit/die unless the error handler returns false
nutshell : your custom error handler effectively determines if E_USER_ERROR is treated as a fatal
2 Comments
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é.
The use of E_USER_ERROR should terminate the script anyway, so moved debug_print_backtrace() before trigger_error().
1 Comment
If you are using PHP 7 or higher, Error class works too:
$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.
1 Comment
Just trying to break our acceptance env. and stumbled upon a nice and simple way to induce a fatal error.
Simply call non existent function. As recommended here
trigger_error()call.