I have a function that tests whether the image received in parameters meets a certain number of criteria (file exists, it is not too large, what type, what compression, etc.).
I would like to set up a try catch block to find out if something goes wrong and to be able to receive a log. Here is the code in function.php
called from main.php
with include("function.php")
:
function check_image($imagePath, $fileType, $targetFile, $imageSize, $courseImage){
$imageStatus=1;
$errors="";
try {
//throw an exception here
$compressionLevel="";
$compressionLevel = ceil($compressionLevel);
} catch (\Throwable $th) {
$errors.="Some error";
$imageStatus =0;
}
return($imagestatus, $errors)
}
And from the main file main.php
I call the function like that:
$result = check_image($imagePath, $fileType, $targetFile, $imageSize, $courseImage);
$imgStatus = $result[0];
$errors = $result[1];
The problem is that if I deliberately trigger an exception (division by zero, type error or other) in the function, the execution stops but nothing is returned. The try catch block does not seem to capture the error.
I read here, for example, that if I implement set_error_handler it should give me something like this:
// Set Error Handler
set_error_handler (
function($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
);
// Trigger an exception in a try block
try {
$a = 3/0;
echo $a;
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
but this also doesn’t seem to give me something back from the function. I want to be able to return the error as parameter of the function. Any idea how to do this? Thanks
PS: The code was actually working fine and sent back an error in the log with:
//faulty code below
try{
$compressionLevel="";
$compressionLevel = ceil($compressionLevel);
}catch (\Throwable $e) { // For PHP 7
$errors.="Throwable error: ".$e->getMessage();
// handle $e
} catch (\Exception $e) { // For PHP 5
// handle $e
$errors.="Exception error";
}
return array($imageStatus,$errors);
But I forgot to output the result in the main.php file like this:
main.php:
$result = check_image($imagePath, $fileType, $targetFile, $imageSize, $courseImage);
$imgStatus = $result[0];
$errors = $result[1];
console_log("What is been sent back from the function -"."\n". $imgStatus . "\n". $errors);
Here is the working result:
Thanks to ADyson who understood the question correctly:
the following code provided is accurate: