PHP natively produces fatal errors when something goes wrong.
These can be handled using a custom error handler,
but they don't permit the use of try-catch blocks in your code.
The following is a quick and painless solution.
<?php
function error_handler_exception($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler('error_handler_exception', E_ERROR);
?>
Now you can enclose things in a try-catch block
and handle the error gracefully.
<?php
try {
do_something();
} catch (Exception $e) {
print "Something broke, and it broke hard.";
}
?>
Happy error handling!
Comments
You need to be logged in to comment on snippets.