I'm trying to add some error checking inside my PHP script. Is it valid to do this:
if (!mkdir($dir, 0)) {
$res->success = false;
$res->error = 'Failed to create directory';
echo json_encode($res);
die;
}
Is there a better way to exit the script after encountering an error like this?
Source: Tips4all, CCNA FINAL EXAM
That looks fine to me.
ReplyDeleteYou can even echo data in the die like so:
if (!mkdir($dir, 0)) {
$res->success = false;
$res->error = 'Failed to create directory';
die(json_encode($res));
}
Throwing a exception. Put code into a try catch block, and throw exception when you need.
ReplyDeletePHP has functions for error triggering and handling.
ReplyDeleteif (!mkdir($dir, 0)) {
trigger_error('Failed to create directory', E_USER_ERROR)
}
When you do this the script will end. The message will be written to the configured error log and it will also be displayed when error_reporting is enabled.